#include "evse_state.h"
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"

static evse_state_t current_state = EVSE_STATE_A;
static bool is_authorized = false;

// Proteção básica para variáveis globais em sistemas concorrentes
static portMUX_TYPE state_mux = portMUX_INITIALIZER_UNLOCKED;

void evse_set_state(evse_state_t state) {
    portENTER_CRITICAL(&state_mux);
    current_state = state;
    portEXIT_CRITICAL(&state_mux);
}

evse_state_t evse_get_state(void) {
    portENTER_CRITICAL(&state_mux);
    evse_state_t s = current_state;
    portEXIT_CRITICAL(&state_mux);
    return s;
}

const char* evse_state_to_str(evse_state_t state) {
    switch (state) {
        case EVSE_STATE_A:  return "A - EV Not Connected (12V)";
        case EVSE_STATE_B1: return "B1 - EV Connected (9V, Not Authorized)";
        case EVSE_STATE_B2: return "B2 - EV Connected (9V, Authorized and Ready)";
        case EVSE_STATE_C1: return "C1 - Charging Requested (6V, Relay Off)";
        case EVSE_STATE_C2: return "C2 - Charging Active (6V, Relay On)";
        case EVSE_STATE_D1: return "D1 - Ventilation Required (3V, Relay Off)";
        case EVSE_STATE_D2: return "D2 - Ventilation Active (3V, Relay On)";
        case EVSE_STATE_E:  return "E - Error: Control Pilot Shorted to Ground (0V)";
        case EVSE_STATE_F:  return "F - Fault: EVSE Unavailable or No Pilot Signal";
        default:            return "Unknown State";
    }
}

void evse_state_init(void) {
    portENTER_CRITICAL(&state_mux);
    current_state = EVSE_STATE_A;
    is_authorized = false;
    portEXIT_CRITICAL(&state_mux);
}

void evse_state_tick(void) {
    // Tick do estado (placeholder)
}

bool evse_state_is_charging(evse_state_t state) {
    return state == EVSE_STATE_C1 || state == EVSE_STATE_C2;
}

bool evse_state_is_plugged(evse_state_t state) {
    return state == EVSE_STATE_B1 || state == EVSE_STATE_B2 ||
           state == EVSE_STATE_C1 || state == EVSE_STATE_C2 ||
           state == EVSE_STATE_D1 || state == EVSE_STATE_D2;
}

bool evse_state_is_session(evse_state_t state) {
    return state == EVSE_STATE_B2 || state == EVSE_STATE_C1 || state == EVSE_STATE_C2;
}

void evse_state_set_authorized(bool authorized) {
    portENTER_CRITICAL(&state_mux);
    is_authorized = authorized;
    portEXIT_CRITICAL(&state_mux);
}

bool evse_state_get_authorized(void) {
    portENTER_CRITICAL(&state_mux);
    bool result = is_authorized;
    portEXIT_CRITICAL(&state_mux);
    return result;
}
