#include "espmega_iot_timer.hpp"

/**
 * @brief Loop function that checks if the timer should run and calls the timer callback function.
 * 
 */
void ESPMega_Timer::loop() {
    rtctime_t curtime = ESPMega_getTime();
    if(today!=curtime.day) {
        today=curtime.day;
        timer_ran_today = false;
        ESPMega_FRAM.write8(fram_address,timer_ran_today);
    }
    if (!timer_ran_today && (hr < curtime.hours || (hr == curtime.hours && min <= curtime.minutes))) {
        timer_ran_today = true;
        ESPMega_FRAM.write8(fram_address,timer_ran_today);
        timer_callback();
    }
}

/**
 * @brief Constructor for ESPMega_Timer class.
 * 
 * @param hour The hour at which the timer should run.
 * @param minute The minute at which the timer should run.
 * @param timer_callback The function to be called when the timer runs.
 * @param fram_address The address in FRAM where the timer state is stored.
 */
ESPMega_Timer::ESPMega_Timer(uint8_t hour,uint8_t minute,void(*timer_callback)(), uint32_t fram_address) {
    this->hr = hour;
    this->min = minute;
    this->timer_callback = timer_callback;
    this->fram_address = fram_address;
}

/**
 * @brief Begins the timer and sets the initial timer state.
 * 
 */
void ESPMega_Timer::begin() {
    rtctime_t curtime = ESPMega_getTime();
    this-> today = curtime.day;
    this-> timer_ran_today = ESPMega_FRAM.read8(fram_address);
    loop();
}

/**
 * @brief Sets the hour and minute at which the timer should run.
 * 
 * @param hour The hour at which the timer should run.
 * @param minute The minute at which the timer should run.
 */
void ESPMega_Timer::set(uint8_t hour,uint8_t minute) {
    rtctime_t curtime = ESPMega_getTime();
    if ((hr < curtime.hours || (hr == curtime.hours && min <= curtime.minutes))) {
        this->timer_ran_today = true;
        ESPMega_FRAM.write8(fram_address,timer_ran_today);
        
    } else {
        this->timer_ran_today = false;
        ESPMega_FRAM.write8(fram_address,timer_ran_today);
    }
    hr = hour;
    min = minute;
}