//#include <proc/p32mx440f256h.h>

#include "LCDCtrl.h"
#include "BoardCfg.h"
#include "timer.h"
#include "hd44780.h"
#include "BatteryMonitor.h"

unsigned int mIsLCDON;
unsigned int mPinStateToggle;

void InitLCDCtrl()
{
	mIsLCDON = 0;
	mPinStateToggle = 0;
	
	LCD_RS_PIN = 0;
	LCD_RW_PIN = 0;
	LCD_E_PIN = 0;
	LCD_DB4_PIN = 0;
	LCD_DB5_PIN = 0;
	LCD_DB6_PIN = 0;
	LCD_DB7_PIN = 0;
//	HD44780_Init();
//	
//	HD44780_DisplayClear();
//	HD44780_PositionXY(0, 0);
//	// send char
//	HD44780_DrawString("Le Chalet");
//	HD44780_PositionXY(0, 1);
//	HD44780_DrawString("Ile aux chevres");
	
	// display clear
	//HD44780_DisplayOn();
	
	TimerStart(LCD_CTRL_TIMER,LCD_REFRESH_TIMEOUT);
}

void TickLCDCtrl()
{
	if(LCD_SCROLL_BTN_PIN == 0)
	{
		if(mPinStateToggle == 0)
		{
			mPinStateToggle = 1;
			if(mIsLCDON == 1)
			{
				mIsLCDON = 0;
				HD44780_DisplayClear();

				LCD_RS_PIN = 0;
				LCD_RW_PIN = 0;
				LCD_E_PIN = 0;
				LCD_DB4_PIN = 0;
				LCD_DB5_PIN = 0;
				LCD_DB6_PIN = 0;
				LCD_DB7_PIN = 0;

			}
			else
			{
				mIsLCDON = 1;
				HD44780_Init();
				HD44780_DisplayClear();
				HD44780_DisplayOn();
			}
		}
	}
	else
	{
		if(mPinStateToggle == 1)
		{
			mPinStateToggle = 0;
		}
	}
	if(IsTimerExpired(LCD_CTRL_TIMER))
	{
		if(mIsLCDON == 1)
		{
			float VBat = GetBatteryVoltage(0);
			float ISolar = GetConvertedSolarPanelCurrent();

			char line1[16], line2[16];
			snprintf(line1,16,"VBat: %.2fV         ",VBat);
			if(ISolar < (float)0.1)
			{
				ISolar *= 1000;
				snprintf(line2,16,"ISol: %.2fmA        ",ISolar);
			}
			else
			{
				snprintf(line2,16,"ISol: %.5fA         ",ISolar);
			}
	//		
	//		HD44780_Init();
	//		HD44780_DisplayClear();
			HD44780_PositionXY(0, 0);
			HD44780_DrawString(line1);

			HD44780_PositionXY(0, 1);
			HD44780_DrawString(line2);

		}
		
		
		TimerStart(LCD_CTRL_TIMER,LCD_REFRESH_TIMEOUT);
	}
}