#include "fire_alarm.h"
#include "serial_control.h"
#include "charger_control.h"
#include "connector.h"
#include "serial.h"
#include "cp.h"
#include "debug.h"

static uint8_t fire_alarm_latched = 0;
static uint32_t fire_alarm_last_estop_tick = 0;

extern CCS_ConnectorState_t CCS_ConnectorState;

uint8_t FireAlarm_IsLatched(void) {
    return fire_alarm_latched;
}

uint8_t FireAlarm_IsBlockingCommand(uint8_t command_code) {
    if (!fire_alarm_latched) {
        return 0;
    }

    switch (command_code) {
        case CMD_GET_STATUS:
        case CMD_GET_INFO:
        case CMD_GET_LOG:
        case CMD_DEVICE_RESET:
            return 0;
        default:
            return 1;
    }
}

void FireAlarm_Activate(void) {
    if (fire_alarm_latched) {
        return;
    }

    fire_alarm_latched = 1;
    CONN.chargingError = CONN_ERR_FIRE_ALARM;
    CONN.connControl = CMD_STOP;
    CONN.EnableOutput = 0;

    log_printf(LOG_ERR, "FIRE ALARM activated\n");

    CCS_SendEmergencyStop();
    fire_alarm_last_estop_tick = HAL_GetTick();
    CP_SetDuty(100);
    CCS_ConnectorState = CCS_DISABLED;
    CONN_SetState(Disabled);
}

void FireAlarm_Maintain(void) {
    if (!fire_alarm_latched) {
        return;
    }

    CONN.chargingError = CONN_ERR_FIRE_ALARM;
    CONN.EnableOutput = 0;
    CP_SetDuty(100);

    if ((int32_t)(HAL_GetTick() - fire_alarm_last_estop_tick) >= 1000) {
        CCS_SendEmergencyStop();
        fire_alarm_last_estop_tick = HAL_GetTick();
    }

    if (CCS_ConnectorState != CCS_DISABLED && CCS_ConnectorState != CCS_UNKNOWN) {
        CCS_ConnectorState = CCS_DISABLED;
    }

    if (CONN.connState != Disabled) {
        CONN_SetState(Disabled);
    }
}
