#include "charger_control.h"

#include "charger_config.h"
#include "debug.h"
#include "fire_alarm.h"
#include "psu_control.h"

ChargingConnector_t CONN;
CONN_State_t connectorState;

void CONN_Init(){

	CONN.connControl = CMD_NONE;
	CONN.connState   = Unknown;
	CONN.RequestedVoltage = PSU_MIN_VOLTAGE;

}

void CONN_Loop(){
    static CONN_State_t last_connState = Unknown;

    if (FireAlarm_IsLatched()) {
        CONN.chargingError = CONN_ERR_FIRE_ALARM;
        CONN.EnableOutput = 0;
        return;
    }

	if(last_connState != CONN.connState){
		last_connState = CONN.connState;
		CONN.connControl = CMD_NONE;
	}

	if(PSU0.cont_fault){
		CONN.chargingError = CONN_ERR_CONTACTOR;
	} else if(PSU0.psu_fault){
		CONN.chargingError = CONN_ERR_PSU_FAULT;
    }else if (CONN.EvConnected == 0){
		CONN.chargingError = CONN_NO_ERROR;
	}

	if(ED_TraceWarning(CONN.chargingError, 0)) {
		log_printf(LOG_WARN, "CONN0 Error: %d\n", (int)CONN.chargingError);
	}

}

void CONN_SetState(CONN_State_t state){
    if (connectorState == state) {
        CONN.connState = state;
        return;
    }

    connectorState = state;

    if(connectorState == Unknown)               log_printf(LOG_INFO, "Connector: Unknown\n");
    if(connectorState == Unplugged)             log_printf(LOG_INFO, "Connector: Unplugged\n");
    if(connectorState == Disabled)              log_printf(LOG_INFO, "Connector: Disabled\n");
    if(connectorState == Preparing)             log_printf(LOG_INFO, "Connector: Preparing\n");
    if(connectorState == AuthRequired)          log_printf(LOG_INFO, "Connector: AuthRequired\n");
    if(connectorState == WaitingForEnergy)      log_printf(LOG_INFO, "Connector: WaitingForEnergy\n");
    if(connectorState == ChargingPausedEV)      log_printf(LOG_INFO, "Connector: ChargingPausedEV\n");
    if(connectorState == ChargingPausedEVSE)    log_printf(LOG_INFO, "Connector: ChargingPausedEVSE\n");
    if(connectorState == Charging)              log_printf(LOG_INFO, "Connector: Charging\n");
    if(connectorState == AuthTimeout)           log_printf(LOG_INFO, "Connector: AuthTimeout\n");
    if(connectorState == Finished)              log_printf(LOG_INFO, "Connector: Finished\n");
    if(connectorState == FinishedEVSE)          log_printf(LOG_INFO, "Connector: FinishedEVSE\n");
    if(connectorState == FinishedEV)            log_printf(LOG_INFO, "Connector: FinishedEV\n");
    if(connectorState == Replugging)            log_printf(LOG_INFO, "Connector: Replugging\n");

    CONN.connState = state;
}
