#include <cmdHelper.h>
#include <logger.h>
#include <string.h>

#include <mbusComm.h>
#include <loopCtrl.h>


// clear statistics
static bool clearCmd(uint8_t argc, char **args) {
    t_mbusCommStats zeroedStats = { .mbusRequestCnt = 0, .mbusErrorCnt = 0, .uartOctetCnt = 0, .uartOverrunCnt = 0, .uartFramingErrCnt = 0, .uartParityErrCnt = 0, .uartNoiseErrCnt = 0 };
    mbusCommSetStats(zeroedStats);
    coloredMsg(LOG_YELLOW, true, "ch cc global statistics cleared");
    return true;
}

static bool mbusCommEnableCmd(uint8_t argc, char **args) {
    bool retCode = true;
    if (argc == 2) {
        if (0 == strcmp("false", args[1])) {
            mbusCommEnable(false);
            coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication disabled");
        } else if (0 == strcmp("true", args[1])) {
            mbusCommEnable(true);
            coloredMsg(LOG_YELLOW, true, "ch mcec Meterbus communication enabled");
        } else {
            retCode = false;
        }
    } else {
        retCode = false;
    }
    return retCode;
}

static bool loopEnableCmd(uint8_t argc, char **args) {
    bool retCode = true;
    if (argc == 2) {
        if (0 == strcmp("false", args[1])) {
            loopDisable();
            coloredMsg(LOG_YELLOW, true, "ch lec loop disabled");
        } else if (0 == strcmp("true", args[1])) {
            loopEnable();
            coloredMsg(LOG_YELLOW, true, "ch lec loop enabled");
        } else {
            retCode = false;
        }
    } else {
        retCode = false;
    }
    return retCode;
}



const cmd_t ADMIN_COMMANDS[] = {
    { .name = "clear", .cmdFunc = clearCmd,
     .help = \
        "clear ................................ Clears the global Meterbus\n\r" \
        "                                       statistics\n\r"
    },
    { .name = "mbusCommEnable", .cmdFunc = mbusCommEnableCmd,
     .help = \
        "mbusCommEnable true|false ............ Enables or disables the Meterbus\n\r" \
        "                                       communication\n\r"
    },
    { .name = "loopEnable", .cmdFunc = loopEnableCmd,
     .help = \
        "loopEnable true|false ................ Enables or disables the loop.\n\r" \
        "                                       Disable Meterbus communication\n\r" \
        "                                       first if you want to disable the\n\r" \
        "                                       for a longer time, otherwise the\n\r" \
        "                                       request will enable it again\n\r"
    },
    { .name = "END_OF_CMDS", .help = "",.cmdFunc = NULL }
};



const cmd_t *getAdminCommands() {
    return ADMIN_COMMANDS;
}