
typedef struct {
  uint16_t year;
  uint8_t month;
  uint8_t day;
  uint8_t hour;
  uint8_t minute;
  uint8_t second;
  uint16_t millisecond;

  bool isAlarmSetup;
  uint8_t alarmHour;
  uint8_t alarmMinute;
  uint8_t alarmSecond;
} Calendar;

Calendar now;
uint8_t dayInMonths[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint32_t Calendar_prevTime;
uint16_t alarmColor;// 0 - alarm off
uint32_t alarmTimer;

void Calendar_Init(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second){
  now.year = year;
  now.month = month;
  now.day = day;
  now.hour = hour;
  now.minute = minute;
  now.second = second;
  now.millisecond = 0;

  now.isAlarmSetup = true;
  now.alarmHour = 14;
  now.alarmMinute = 00;
  now.alarmSecond = 10;

  alarmColor = 0;
  alarmTimer = 0;

  Calendar_prevTime = millis();
}

void Calendar_Update(){
  now.millisecond += millis() - Calendar_prevTime;
  Calendar_prevTime = millis();

  if(now.millisecond >= 1000){
    now.millisecond-=1000;
    now.second++;
  }

  if(now.second >= 60){
    now.second-=60;
    now.minute++;
  }

  if(now.minute >= 60){
    now.minute-=60;
    now.hour++;
  }

  if(now.hour >= 24){
    now.hour-=24;
    now.day++;
  }

  if(now.day >= dayInMonths[now.month]){
    now.day = 1;
    now.month++;
  }

  if(now.month >= 12){
    now.month-=12;
    now.year++;
  }

  if(alarmColor == 0 && now.second == now.alarmSecond && now.minute == now.alarmMinute && now.hour == now.alarmHour){
    alarmColor = 1;
  }

  if(alarmColor != 0){
    if(millis() > alarmTimer){
      if(alarmColor != 1000) {
        RGB_SetColor(50, 0, 0);
        alarmColor = 1000;
      }
      else {
        RGB_SetColor(0, 0, 50);
        alarmColor = 500;
      }
      
      //tone(9, alarmFreq);

      alarmTimer = millis() + 500;
    }

    if(Joystick_isButtonPressed(JOYSTICK_CENTER) || IR_isButtonPressed(IRButton_OK)){
      alarmColor = 0;
      //alarmFreq = 0;
      alarmTimer = 0;
      //noTone(9);
      RGB_SetColor(0, 0, 0);
    }
  }


}

bool Calendar_EditDate(uint8_t day, uint8_t month, uint16_t year){
  if(year > 9999 || year < 1) return false;
  if(month < 1 || month > 12) return false;
  if(day < 1 || day > dayInMonths[month]) return false;

  now.year = year;
  now.month = month;
  now.day = day;
  return true;
}

bool Calendar_EditTime(uint8_t hour, uint8_t minute, uint8_t second){
  if(hour > 23) return false;
  if(minute > 59) return false;
  if(second > 59) return false;

  now.hour = hour;
  now.minute = minute;
  now.second = second;
  return true;
}

bool Calendar_SetupAlarm(uint8_t hour, uint8_t minute, uint8_t second){
  if(hour > 23) return false;
  if(minute > 59) return false;
  if(second > 59) return false;

  now.isAlarmSetup = true;
  now.alarmHour = hour;
  now.alarmMinute = minute;
  now.alarmSecond = second;
  return true;
}

void Calendar_DisableAlarm(){
  now.isAlarmSetup = false;
  now.alarmHour = 0;
  now.alarmMinute = 0;
  now.alarmSecond = 0;
}