#include "loadbalancer.h"
#include "gridmeter.h"
#include "evsemeter.h"
#include "evse_api.h"
#include "esp_event.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

static const char *TAG = "loadbalancer";

static float grid_current = 0.0f;
static float evse_current = 0.0f;
static float max_grid_current = 32.0f; // amperes

static void grid_event_handler(void *arg, esp_event_base_t base, int32_t id, void *data)
{
    if (id == GRIDMETER_EVENT_UPDATE && data)
    {
        grid_current = *(float *)data;
    }
}

static void evse_event_handler(void *arg, esp_event_base_t base, int32_t id, void *data)
{
    if (id == EVSEMETER_EVENT_UPDATE && data)
    {
        evse_current = *(float *)data;
    }
}

void loadbalancer_init(void)
{
    ESP_LOGI(TAG, "Initializing load balancer");
    esp_event_handler_register(GRIDMETER_EVENT, GRIDMETER_EVENT_UPDATE, grid_event_handler, NULL);
    esp_event_handler_register(EVSEMETER_EVENT, EVSEMETER_EVENT_UPDATE, evse_event_handler, NULL);
}

void loadbalancer_task(void *param)
{
    while (true)
    {
        float available = max_grid_current - grid_current + evse_current;
        if (available < 6.0f)
        {
            available = 6.0f;
        }
        ESP_LOGD(TAG, "Setting current limit: %f", available);
        evse_set_current_limit((uint16_t)available);
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void setMaxGridCurrent(int value)
{
    max_grid_current = value / 10.0f; // assume value in A*10
}

void setLiveGridCurrent(int value)
{
    grid_current = value / 10.0f;
}

void setLiveVolt(int value)
{
    (void)value; // unused for now
}
