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

CContrastDialog ContrastDialog;

#define CONTRAST_STEP 5

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

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

	OnDraw();
}

void CContrastDialog::OnEncoderCW(void)
{
	lcd_uc1601s_pm += CONTRAST_STEP;

	if (lcd_uc1601s_pm > configure_file.max_lcd_uc1601s_pm)
	{
		lcd_uc1601s_pm = configure_file.max_lcd_uc1601s_pm;
		beep(10);
	}

	flash_file * p_flash_file;

	fseek(p_flash, (int) (&p_flash_file->lcd_uc1601s_pm) - (int) (p_flash_file), SEEK_SET);
	fwrite(&lcd_uc1601s_pm, sizeof(flash_file::lcd_uc1601s_pm), 1, p_flash);

	fflush(p_flash);

	freopen("lcd", "rb+", p_lcd);
	setvbuf(p_lcd, nullptr, _IOFBF, 16);

	OnDraw();
}

void CContrastDialog::OnEncoderCCW(void)
{
	lcd_uc1601s_pm -= CONTRAST_STEP;

	if (lcd_uc1601s_pm < configure_file.min_lcd_uc1601s_pm)
	{
		lcd_uc1601s_pm = configure_file.min_lcd_uc1601s_pm;
		beep(10);
	}

	flash_file * p_flash_file;

	fseek(p_flash, (int) (&p_flash_file->lcd_uc1601s_pm) - (int) (p_flash_file), SEEK_SET);
	fwrite(&lcd_uc1601s_pm, sizeof(flash_file::lcd_uc1601s_pm), 1, p_flash);

	fflush(p_flash);

	freopen("lcd", "rb+", p_lcd);
	setvbuf(p_lcd, nullptr, _IOFBF, 16);

	OnDraw();
}

void CContrastDialog::OnButtonDown(void)
{
	p_dialog = &SettingDialog;
	p_dialog->OnCreat();
}

void CContrastDialog::OnDraw(void)
{
	rewind(p_lcd);
	fputs("LCD contrast:", p_lcd);

	fseek(p_lcd, 16, SEEK_SET);
	fputs("turn knob to", p_lcd);

	fseek(p_lcd, 32, SEEK_SET);
	fputs("adjust contrast", p_lcd);

	fseek(p_lcd, 53, SEEK_SET);
	fputs("Return", p_lcd);

	fseek(p_lcd, 117, SEEK_SET);
	fputs("\x1\x1\x1\x1\x1\x1", p_lcd);

	fflush(p_lcd);
}

