#include <applications/dialog/AddressDialog.h>
#include <cstdio>
#include <hal/devices.h>
#include <hal/drivers/buzzer.h>
#include <applications/dialog/SettingDialog.h>

CAddressDialog AddressDialog;

void CAddressDialog::OnCreat(void)
{
	rewind(p_lcd);
	fwrite(zeros, 128, 1, p_lcd);

	rewind(p_lcd);
	fputs("RS-485 Address:", p_lcd);

	fseek(p_lcd, 48, SEEK_SET);
	fputs("  Save   Cancel", p_lcd);

	in_edit = false;
	menu_item = adr;

	flash_file * p_flash_file;
	fseek(p_flash, (int) (&p_flash_file->rs485_address) - (int) (p_flash_file), SEEK_SET);
	fread(&address, sizeof(flash_file::rs485_address), 1, p_flash);

	OnDraw();
}

void CAddressDialog::OnEncoderCW(void)
{
	if (in_edit)
	{
		if (address >= configure_file.max_rs485_address)
		{
			beep(10);
			return;
		}
		else
		{
			++address;
		}
	}
	else
	{
		switch (menu_item)
		{
		default:
		case adr:
			menu_item = save;
			break;
		case save:
			menu_item = cancel;
			break;
		case cancel:
			beep(10);
			return;
			break;
		}
	}

	OnDraw();
}

void CAddressDialog::OnEncoderCCW(void)
{
	if (in_edit)
	{
		if (address <= configure_file.min_rs485_address)
		{
			beep(10);
			return;
		}
		else
		{
			--address;
		}
	}
	else
	{
		switch (menu_item)
		{
		case adr:
			beep(10);
			return;
			break;
		case save:
			menu_item = adr;
			break;
		default:
		case cancel:
			menu_item = save;
			break;
		}
	}

	OnDraw();
}

void CAddressDialog::OnButtonDown(void)
{
	flash_file * p_flash_file;

	switch (menu_item)
	{
	default:
		menu_item = adr;
	case adr:
		in_edit = !in_edit;
		break;
	case save:
		fseek(p_flash, (int) (&p_flash_file->rs485_address) - (int) (p_flash_file), SEEK_SET);
		fwrite(&address, sizeof(flash_file::rs485_address), 1, p_flash);
		fflush(p_flash);
	case cancel:
		p_dialog = &SettingDialog;
		p_dialog->OnCreat();
		return;
		break;
	}

	OnDraw();
}

void CAddressDialog::OnDraw(void)
{
	fseek(p_lcd, 102, SEEK_SET);
	fwrite(zeros, 3, 1, p_lcd);

	fseek(p_lcd, 112, SEEK_SET);
	fwrite(zeros, 16, 1, p_lcd);

	fseek(p_lcd, 38, SEEK_SET);
	fprintf(p_lcd, "%3i", address);

	switch (menu_item)
	{
	default:
		menu_item = adr;
	case adr:
		fseek(p_lcd, 102, SEEK_SET);
		if (in_edit)
		{
			fputs("\2\2\2", p_lcd);
		}
		else
		{
			fputs("\1\1\1", p_lcd);
		}
		break;
	case save:
		fseek(p_lcd, 112, SEEK_SET);
		fputs("\1\1\1\1\1\1\1\1", p_lcd);
		break;
	case cancel:
		fseek(p_lcd, 120, SEEK_SET);
		fputs("\1\1\1\1\1\1\1\1", p_lcd);
		break;
	}

	fflush(p_lcd);
}

