#include "v2g_context.h"

int v2g_context_init(v2g_context_t* v2g, const char* if_name)
{
    if (v2g)
    {
        secc_port_t *secc = (secc_port_t*)v2g->secc;

        printd("V2G start...\n");
        v2g->quit = 0;
        secc->SECC_maxV = 1000;
        secc->SECC_minV = 150;
        secc->SECC_maxI = 250;
        secc->SECC_minI = 0.5;
        secc->SECC_maxP = 80000;

        secc->EVCC_maxI = 0;
        secc->EVCC_maxV = 0;
        secc->EVCC_maxP = 0;

        secc->limit_DefaultCurrent = 0;
        secc->limit_DefaultPowerKW = 0;
        secc->limit_TxCurrent = 0;
        secc->limit_TxPowerKW = 0;

        v2g->evse_isolation_status = din_isolationLevelType_Invalid;
        v2g->evse_notification = 0;

        v2g->evse_status_code[PHASE_INIT] = iso2_DC_EVSEStatusCodeType_EVSE_NotReady;
        v2g->evse_status_code[PHASE_AUTH] = iso2_DC_EVSEStatusCodeType_EVSE_NotReady;
        v2g->evse_status_code[PHASE_PARAMETER] = iso2_DC_EVSEStatusCodeType_EVSE_Ready; // [V2G-DC-453]
        v2g->evse_status_code[PHASE_ISOLATION] = iso2_DC_EVSEStatusCodeType_EVSE_IsolationMonitoringActive;
        v2g->evse_status_code[PHASE_PRECHARGE] = iso2_DC_EVSEStatusCodeType_EVSE_Ready;
        v2g->evse_status_code[PHASE_CHARGE] = iso2_DC_EVSEStatusCodeType_EVSE_Ready;
        v2g->evse_status_code[PHASE_WELDING] = iso2_DC_EVSEStatusCodeType_EVSE_NotReady;
        v2g->evse_status_code[PHASE_STOP] = iso2_DC_EVSEStatusCodeType_EVSE_NotReady;
        memset(v2g->evse_processing, iso2_EVSEProcessingType_Ongoing, PHASE_LENGTH);

        v2g->iso_selected_payment_option = iso2_paymentOptionType_ExternalPayment;
        v2g->auth_timeout_pnc = 3600000;
        v2g->auth_timeout_eim = 3600000;
        v2g->if_name = if_name;

        v2g->sdp_server_quit = 1;
        v2g->tcp_server_quit = 1;
        v2g->tls_server_quit = 1;
        v2g->sdp_socket = -1;
        v2g->tcp_socket = -1;
        v2g->tls_socket = -1;
        v2g->next_client = NULL;
        v2g->current_v2g_msg = 0;
        v2g->state = 0;
        // v2g_tls_server_init(v2g);
        v2g_tcp_server_init(v2g);
        v2g_sdp_server_init(v2g);
        
        return 0;
    }
    return -1;
}

void v2g_context_exit(v2g_context_t* v2g)
{
    secc_port_t *secc = (secc_port_t*)v2g->secc;
    evse_slac_t* slac = (evse_slac_t*)&v2g->evse_slac;

    if (v2g)
    {
        printd("V2G stop...\n");
        v2g_sdp_server_exit(v2g);
        v2g_tcp_server_exit(v2g);
        // v2g_tls_server_exit(v2g);
    }
}

float calc_physical_value(const int16_t value, const int8_t multiplier) 
{
    return (float)(value * pow(10.0, multiplier));
}

