#include "evse_manager.h"
#include "evse_state.h"
#include "evse_error.h"
#include "evse_hardware.h"
#include "evse_config.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_log.h"

static const char *TAG = "evse_manager";

static SemaphoreHandle_t evse_mutex;

#define EVSE_MANAGER_TICK_PERIOD_MS 1000  // 1 segundo



void evse_manager_init(void) {
    evse_mutex = xSemaphoreCreateMutex();
   
    evse_config_init();
    evse_error_init();
    evse_hardware_init();
    evse_state_init();
    ESP_LOGI(TAG, "EVSE Manager initialized");

    xTaskCreate(
        evse_manager_task,
        "evse_manager_task",
        4096,       // stack size
        NULL,       // param
        5,          // priority
        NULL        // handle
    );
}

void evse_manager_task(void *arg) {
    while (true) {
        evse_manager_tick();
        vTaskDelay(pdMS_TO_TICKS(EVSE_MANAGER_TICK_PERIOD_MS));
    }
}


void evse_manager_tick(void) {
    xSemaphoreTake(evse_mutex, portMAX_DELAY);

    // Atualizações cíclicas de módulos
    evse_hardware_tick();
    evse_error_tick();
    evse_state_tick();

    evse_temperature_check();

    xSemaphoreGive(evse_mutex);
}

bool evse_manager_is_available(void) {
    return evse_config_is_available();
}

void evse_manager_set_available(bool available) {
    evse_config_set_available(available);
}

void evse_manager_set_authorized(bool authorized) {
    evse_state_set_authorized(authorized);
}

bool evse_manager_is_charging(void) {
    return evse_state_is_charging(evse_get_state());
}

void evse_manager_set_enabled(bool enabled) {
    evse_config_set_enabled(enabled);
}

bool evse_manager_is_enabled(void) {
    return evse_config_is_enabled();
}
