#include "load.h"
#include "board.h"
#include "debug.h"
#include "connector.h"

#define COOLDOWN_TIME 60000

static void LOAD_LogEnableChanges(void){
    static uint8_t inited = 0U;
    static uint8_t prev_enable_0 = 0U;
    static uint8_t prev_enable_1 = 0U;

    if(!inited){
        prev_enable_0 = CONN[0].enableLoad;
        prev_enable_1 = CONN[1].enableLoad;
        inited = 1U;
        return;
    }

    if(prev_enable_0 != CONN[0].enableLoad){
        log_printf(LOG_INFO, "GBT Load %s\n", CONN[0].enableLoad ? "enabled" : "disabled");
        prev_enable_0 = CONN[0].enableLoad;
    }
    if(prev_enable_1 != CONN[1].enableLoad){
        log_printf(LOG_INFO, "CCS Load %s\n", CONN[1].enableLoad ? "enabled" : "disabled");
        prev_enable_1 = CONN[1].enableLoad;
    }
}

void LOAD_Init(){
	RELAY_Write(RELAY_1, 0);
	RELAY_Write(RELAY_2, 0);
	RELAY_Write(RELAY_3, 0);
    RELAY_Write(RELAY_4, 0);
	RELAY_Write(RELAY_5, 0);
}

void LOAD_Task(){
    static uint32_t load_tick = 0;
    LOAD_LogEnableChanges();

    if(CONN[0].enableLoad || CONN[1].enableLoad){
        load_tick = HAL_GetTick();
    }

    if((HAL_GetTick() - load_tick < COOLDOWN_TIME) && (load_tick!=0)){
        RELAY_Write(RELAY_1, 1);
    }else{
        RELAY_Write(RELAY_1, 0);
    }


	if(CONN[0].enableLoad){
		RELAY_Write(RELAY_2, 1);
	}else{
		RELAY_Write(RELAY_2, 0);
	}
	if(CONN[1].enableLoad){
		RELAY_Write(RELAY_3, 1);
	}else{
		RELAY_Write(RELAY_3, 0);
	}

    // if(CONN[0].enableLoad && CONN[1].enableLoad){ // объединение нагрузок
    //     RELAY_Write(RELAY_4, 0);
    // }else{
    //     RELAY_Write(RELAY_4, 1);
    // }
}