//Joystick button codes
#define JOYSTICK_UP 1
#define JOYSTICK_CENTER 2
#define JOYSTICK_LEFT 3
#define JOYSTICK_DOWN 4
#define JOYSTICK_RIGHT 5
//IR remote button codes 
#define IRButton_1 1
#define IRButton_2 2
#define IRButton_3 3
#define IRButton_4 4
#define IRButton_5 5
#define IRButton_6 6
#define IRButton_7 7
#define IRButton_8 8
#define IRButton_9 9
#define IRButton_STAR 10 //*
#define IRButton_0 11 
#define IRButton_SHARP 12 //#
#define IRButton_UP 13
#define IRButton_LEFT 14 
#define IRButton_OK 15 
#define IRButton_RIGHT 16 
#define IRButton_DOWN 17 

extern Calendar now;

uint8_t month, day, hour, minute, second;
bool lampState = false;
bool alarmState = false;

String monthLabels[] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

AppState DisplayScreen(LiquidCrystal_I2C* lcd, AppState prevAppState){
  //Init
  if(prevAppState != APPSTATE_DISPLAY){
      lcd->clear();
      lcd->home();
      lcd->print("00,Jan  00:00:00");

      lcd->setCursor(0,1);
      lcd->print("Alarm:Off");

      lcd->setCursor(15,1);
      lcd->write(lampState);

      month = 0; day = 0; hour = 0; minute = 0; second = 0;
  }

  //Update day display
  if(day != now.day){
    day = now.day;
    lcd->setCursor(0,0);
    if(day < 10) lcd->print("0");
    lcd->print(day);
  }
  //Update month display
  if(month != now.month){
    month = now.month;
    lcd->setCursor(3,0);
    lcd->print(monthLabels[month]);
  }
  //Update hour display
  if(hour != now.hour){
    hour = now.hour;
    lcd->setCursor(8,0);
    if(hour < 10) lcd->print(" ");
    lcd->print(hour);
  }
  //Update minute display
  if(minute != now.minute){
    minute = now.minute;
    lcd->setCursor(11,0);
    if(minute < 10) lcd->print("0");
    lcd->print(minute);
  }
  //Update second display
  if(second != now.second){
    second = now.second;
    lcd->setCursor(14,0);
    if(second < 10) lcd->print("0");
    lcd->print(second);
  }

  //Update alarm state
  if(alarmState != now.isAlarmSetup){
    alarmState = now.isAlarmSetup;
    lcd->setCursor(6,1);
    if(alarmState) lcd->print("On ");
    else lcd->print("Off");
  }

  //Update lamp state
  if(lampState == true && Photosensor_Read() > 30){
      lampState = false;
      RGB_SetColor(0, 0, 0);
      lcd->setCursor(15,1);
      lcd->write(lampState);
  }
  if(lampState == false && Photosensor_Read() < 25){
      lampState = true;
      RGB_SetColor(50, 50, 50);
      lcd->setCursor(15,1);
      lcd->write(lampState);
  }

  if(Joystick_isButtonPressed(JOYSTICK_CENTER) || IR_isButtonPressed(IRButton_OK)){
    return APPSTATE_SETTINGS;
  }
  
  return APPSTATE_DISPLAY;
}

