#include <stdio.h>
#include <cJSON.h>
#include <esp_log.h>
#include "washingMachineState.h"
#include <time.h>

#define TAG "WMS"

WashingMachineState wms;

WashingMachineState traiteMessage(char* message){

        cJSON *root = cJSON_Parse(message);
        char* json = cJSON_PrintUnformatted(root);
        ESP_LOGE(TAG, "%s", json);
        
        bool state = cJSON_IsTrue(cJSON_GetObjectItem(root, "state"));
        double timestamp = cJSON_GetNumberValue(cJSON_GetObjectItem(root, "timestamp"));
        bool ack = cJSON_HasObjectItem(root,"ack") && cJSON_GetNumberValue(cJSON_GetObjectItem(root,"ack"));

        //char dateStr[80] ;
        //timestampToDate(timestamp,dateStr,80);

        wms.etat = state?LAVEUSE_LAVAGE:LAVEUSE_ARRET;
        wms.depuis = timestamp;
        wms.ack = ack;

        cJSON_Delete(root);

        return wms;
}

void timestampToDate(double timestamp, char* dateStr, size_t dateStrSize)
{
    time_t ts = timestamp;
    struct tm *pTime = localtime(&ts);

    strftime(dateStr, dateStrSize, "%d/%m/%Y %H:%M:%S", pTime);
    //printf("Date and french time : %s\n", dateStr);
}

WashingMachineState getEtatMachine(){
    return wms;
}

void getEtatMachineStr(WashingMachineState wms, char* etat, size_t etatSize)
{
    char* etatStr;
    switch (wms.etat)
    {
    case LAVEUSE_ARRET:
        /* code */
        etatStr="Machine arretée";
        break;
    
    case LAVEUSE_LAVAGE:
        /* code */
        etatStr="Machine en route";
        break;

        default:
        etatStr="Etat inconnu";
        break;
    }
    char dateStr[30];
    timestampToDate(wms.depuis,dateStr,30);
    
    snprintf(etat,etatSize,"%s depuis %s", etatStr, dateStr);
    ESP_LOGE(TAG,"%s",etat);

}

void acknoledge(){
    wms.ack=true;
}
