#include <stdbool.h>

#include <main.h>
#include <adc.h>

#include <frontend.h>
#include <logger.h>
#include <show.h>
#include <config.h>


static t_configBlock *config;


static volatile int32_t frontendAdcThreshold = 0;
static volatile bool frontendEnabled = false;


void frontendInit() {
    config = getConfig();
    frontendAdcThreshold = config->frontendThreshold;
    
    HAL_ADCEx_Calibration_Start(&frontendAdc);
    logMsg("frontendInit, calibration done");
    HAL_ADC_Start_IT(&frontendAdc);
    logMsg("frontendInit, adc started");
}

void frontendEnable() {
    frontendEnabled = true;
}

void frontendDisable() {
    frontendEnabled = false;
}

void frontendAdcCallback(ADC_HandleTypeDef* hadc) {
    static int32_t holdValue = 0;

    if (frontendEnabled) {
        int32_t currentValue = (int32_t) HAL_ADC_GetValue(hadc);

        if (holdValue == 0) {
            holdValue = currentValue;
        }

        if (currentValue - holdValue > frontendAdcThreshold) {
            HAL_GPIO_WritePin(Frontend_Out_GPIO_Port, Frontend_Out_Pin, GPIO_PIN_RESET);
        } else {
            HAL_GPIO_WritePin(Frontend_Out_GPIO_Port, Frontend_Out_Pin, GPIO_PIN_SET);
        }
    } else {
        if (holdValue != 0) {
            holdValue = 0;
            HAL_GPIO_WritePin(Frontend_Out_GPIO_Port, Frontend_Out_Pin, GPIO_PIN_SET);
        }
    }

}
