#include "debugger.h"

DebugStatus_t DebuggerStatus[dbg_cntElements];

String IpAddress2String(const IPAddress &ipAddress);
void processCmdDebug();
void Debug_formatCFG();
void Debug_formatPersistence();
void Debug_printSystemInfo();
void Debug_printWifiInfo();
void Debug_CheckEEPOM();
void Debug_dumpConfig();
void Debug_dumpPersistance();
void Debug_ShowDTCs();
void Debug_dumpGlobals();

void initDebugger()
{
    DebuggerStatus[dbg_Serial] = disabled;
    DebuggerStatus[dbg_Webui] = disabled;

    Serial.setDebugOutput(false);
}

void SetDebugportStatus(DebugPorts_t port, DebugStatus_t status)
{
    if (status == disabled)
        Debug_pushMessage("disable DebugPort %s", sDebugPorts[port]);

    DebuggerStatus[port] = status;

    if (status == enabled)
        Debug_pushMessage("enabled DebugPort %s", sDebugPorts[port]);
}

void Debug_pushMessage(const char *format, ...)
{
    if ((DebuggerStatus[dbg_Serial] == enabled) || (DebuggerStatus[dbg_Webui] == enabled))
    {
        char buff[64];
        va_list arg;
        va_start(arg, format);
        vsnprintf(buff, sizeof(buff), format, arg);
        va_end(arg);

        if (DebuggerStatus[dbg_Serial] == enabled)
        {
            Serial.print(buff);
        }
        if (DebuggerStatus[dbg_Webui] == enabled)
        {
            Websocket_PushLiveDebug(String(buff));
        }
    }
}

void pushCANDebug(uint32_t id, uint8_t dlc, uint8_t *data)
{
    if ((DebuggerStatus[dbg_Serial] == enabled) || (DebuggerStatus[dbg_Webui] == enabled))
    {
        char buff[100];
        char *p = buff;
        p += snprintf(p, sizeof(buff), "CAN: 0x%08X | %d | ", id, dlc);
        for (int i = 0; i < dlc; i++)
        {
            p += snprintf(p, sizeof(buff) - (p - buff), "%02X ", data[i]);
        }
        *(p++) = '\n';
        *p = '\0';

        if (DebuggerStatus[dbg_Serial] == enabled)
        {
            Serial.print(buff);
        }
        if (DebuggerStatus[dbg_Webui] == enabled)
        {
            Websocket_PushLiveDebug(String(buff));
        }
    }
}

void processCmdDebug(String command)
{
    if (command == "sysinfo")
        Debug_printSystemInfo();
    else if (command == "netinfo")
        Debug_printWifiInfo();
    else if (command == "formatCFG")
        Debug_formatCFG();
    else if (command == "formatPDS")
        Debug_formatPersistence();
    else if (command == "checkEE")
        Debug_CheckEEPOM();
    else if (command == "dumpEE1k")
        dumpEEPROM(0, 1024);
    else if (command == "dumpEE")
        dumpEEPROM(0, EEPROM_SIZE_BYTES);
    else if (command == "resetPageEE")
        MovePersistencePage_EEPROM(true);
    else if (command == "dumpCFG")
        Debug_dumpConfig();
    else if (command == "dumpPDS")
        Debug_dumpPersistance();
    else if (command == "saveEE")
        globals.requestEEAction = EE_ALL_SAVE;
    else if (command == "showdtc")
        Debug_ShowDTCs();
    else if (command == "dumpGlobals")
        Debug_dumpGlobals();
}

void Debug_formatCFG()
{
    Debug_pushMessage("Formatting Config-EEPROM and reseting to default");
    FormatConfig_EEPROM();
}

void Debug_formatPersistence()
{
    Debug_pushMessage("Formatting Persistence-EEPROM and reseting to default");
    FormatPersistence_EEPROM();
}

void RemotDebug_printSystemInfo()
{
    Debug_pushMessage("Souko's ChainOiler Mk1");
    Debug_pushMessage("Hostname: %s", globals.DeviceName);

    FlashMode_t ideMode = ESP.getFlashChipMode();
    Debug_pushMessage("Sdk version: %s", ESP.getSdkVersion());
    Debug_pushMessage("Core Version: %s", ESP.getCoreVersion().c_str());
    Debug_pushMessage("Boot Version: %u", ESP.getBootVersion());
    Debug_pushMessage("Boot Mode: %u", ESP.getBootMode());
    Debug_pushMessage("CPU Frequency: %u MHz", ESP.getCpuFreqMHz());
    Debug_pushMessage("Reset reason: %s", ESP.getResetReason().c_str());
    Debug_pushMessage("Flash Size: %d", ESP.getFlashChipRealSize());
    Debug_pushMessage("Flash Size IDE: %d", ESP.getFlashChipSize());
    Debug_pushMessage("Flash ide mode:  %s", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT"
                                                           : ideMode == FM_DIO    ? "DIO"
                                                           : ideMode == FM_DOUT   ? "DOUT"
                                                                                  : "UNKNOWN"));
    Debug_pushMessage("OTA-Pass: %s", QUOTE(ADMIN_PASSWORD));
    Debug_pushMessage("Git-Revison: %s", GIT_REV);
    Debug_pushMessage("Sw-Version: %s", QUOTE(SW_VERSION));
}

void Debug_dumpConfig()
{
    Debug_pushMessage("DistancePerLube_Default: %d", LubeConfig.DistancePerLube_Default);
    Debug_pushMessage("DistancePerLube_Rain: %d", LubeConfig.DistancePerLube_Rain);
    Debug_pushMessage("tankCapacity_ml: %d", LubeConfig.tankCapacity_ml);
    Debug_pushMessage("amountPerDose_microL: %d", LubeConfig.amountPerDose_microL);
    Debug_pushMessage("TankRemindAtPercentage: %d", LubeConfig.TankRemindAtPercentage);
    Debug_pushMessage("PulsePerRevolution: %d", LubeConfig.PulsePerRevolution);
    Debug_pushMessage("TireWidth_mm: %d", LubeConfig.TireWidth_mm);
    Debug_pushMessage("TireWidthHeight_Ratio: %d", LubeConfig.TireWidth_mm);
    Debug_pushMessage("RimDiameter_Inch: %d", LubeConfig.RimDiameter_Inch);
    Debug_pushMessage("DistancePerRevolution_mm: %d", LubeConfig.DistancePerRevolution_mm);
    Debug_pushMessage("BleedingPulses: %d", LubeConfig.BleedingPulses);
    Debug_pushMessage("SpeedSource: %d", LubeConfig.SpeedSource);
#ifdef FEATURE_ENABLE_GPS
    Debug_pushMessage("GPSBaudRate: %d", LubeConfig.GPSBaudRate);
#endif
#ifdef FEATURE_ENABLE_CAN
    Debug_pushMessage("CANSource: %d", LubeConfig.CANSource);
#endif
    Debug_pushMessage("checksum: 0x%08X", LubeConfig.checksum);
}

void Debug_dumpGlobals()
{
    Debug_pushMessage("systemStatus: %d", globals.systemStatus);
    Debug_pushMessage("resumeStatus: %d", globals.resumeStatus);
    Debug_pushMessage("systemStatustxt: %s", globals.systemStatustxt);
    Debug_pushMessage("purgePulses: %d", globals.purgePulses);
    Debug_pushMessage("requestEEAction: %d", globals.requestEEAction);
    Debug_pushMessage("DeviceName: %s", globals.DeviceName);
    Debug_pushMessage("FlashVersion: %s", globals.FlashVersion);
    Debug_pushMessage("eePersistanceAdress: %d", globals.eePersistanceAdress);
    Debug_pushMessage("TankPercentage: %d", globals.TankPercentage);
    Debug_pushMessage("hasDTC: %d", globals.hasDTC);
}

void Debug_dumpPersistance()
{
    Debug_pushMessage("writeCycleCounter: %d", PersistenceData.writeCycleCounter);
    Debug_pushMessage("tankRemain_microL: %d", PersistenceData.tankRemain_microL);
    Debug_pushMessage("TravelDistance_highRes_mm: %d", PersistenceData.TravelDistance_highRes_mm);
    Debug_pushMessage("checksum: %d", PersistenceData.checksum);
    Debug_pushMessage("PSD Adress: 0x%04X", globals.eePersistanceAdress);
}

void Debug_printWifiInfo()
{
}

void Debug_CheckEEPOM()
{
    uint32_t checksum = PersistenceData.checksum;
    PersistenceData.checksum = 0;

    if (Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData)) == checksum)
    {
        Debug_pushMessage("PersistenceData EEPROM Checksum OK\n");
    }
    else
    {
        Debug_pushMessage("PersistenceData EEPROM Checksum BAD\n");
    }

    PersistenceData.checksum = checksum;

    checksum = LubeConfig.checksum;
    LubeConfig.checksum = 0;

    if (Checksum_EEPROM((uint8_t *)&LubeConfig, sizeof(LubeConfig)) == checksum)
    {
        Debug_pushMessage("LubeConfig EEPROM Checksum OK\n");
    }
    else
    {
        Debug_pushMessage("LubeConfig EEPROM Checksum BAD\n");
    }
    LubeConfig.checksum = checksum;
}

void Debug_ShowDTCs()
{
    char buff_timestamp[16]; // Format: DD-hh:mm:ss:xxx
    char buff_active[9];

    for (uint32_t i = 0; i < MAX_DTC_STORAGE; i++)
    {
        if (DTCStorage[i].Number < DTC_LAST_DTC)
        {
            sprintf(buff_timestamp, "%02d-%02d:%02d:%02d:%03d",
                    DTCStorage[i].timestamp / 86400000,    // Days
                    DTCStorage[i].timestamp / 360000 % 24, // Hours
                    DTCStorage[i].timestamp / 60000 % 60,  // Minutes
                    DTCStorage[i].timestamp / 1000 % 60,   // Seconds
                    DTCStorage[i].timestamp % 1000);       // milliseconds

            if (DTCStorage[i].active == DTC_ACTIVE)
                strcpy(buff_active, "active");
            else if (DTCStorage[i].active == DTC_PREVIOUS)
                strcpy(buff_active, "previous");
            else
                strcpy(buff_active, "none");

            Debug_pushMessage("%s \t %6d \t %s \t %d", buff_timestamp, DTCStorage[i].Number, buff_active, DTCStorage[i].severity);
        }
    }
}