#include "cmds.h"
#include "Drivers/EthDrv/phy_drv/phy_common.h"
#include "audio/audio.h"
#include "cliutils/cli.h"

#include <stdlib.h>
#include <string.h>

#include "FreeRTOS.h"
#include "cmsis_os2.h"

#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "portable.h"
#include "standard_output/standard_output.h"           

#include <stm32h7xx.h>


CMD_FUNCTION(os_info) {
    osVersion_t kVersion;
    char kId[32];
    kId[sizeof(kId) - 1] = 0;
    osKernelGetInfo(&kVersion, kId, sizeof(kId) - 1);
    MSG("OS: %s\n Kernel version: %d\n API version: %d\n", kId, kVersion.kernel, kVersion.api);

    HeapStats_t stats;
    vPortGetHeapStats(&stats);
    MSG("Free OS memory: %u bytes\n", stats.xAvailableHeapSpaceInBytes);

    return 0;
}

CMD_FUNCTION(phy_info) {
    phy_print_full_name();
    return 0;
}

CMD_FUNCTION(print_ip) {
    MSG("IP: " ANSI_COLOR_BYELLOW "%s" ANSI_COLOR_RESET "\n", ipaddr_ntoa(&(netif_default->ip_addr)));
    MSG("Gateway: %s\n", ipaddr_ntoa(&(netif_default->gw)));
    MSG("Netmask: %s\n", ipaddr_ntoa(&(netif_default->netmask)));
    MSGraw(ANSI_COLOR_RESET "\r\n");
    return 0;
}

#define HWA_SEMI ANSI_COLOR_RESET ":" ANSI_COLOR_BYELLOW

CMD_FUNCTION(print_hwa) {
    MSGraw("Hardware address:\r\n" ANSI_COLOR_BYELLOW);
    uint8_t * hwa = netif_default->hwaddr;
    MSG("%02X" HWA_SEMI "%02X" HWA_SEMI "%02X" HWA_SEMI "%02X" HWA_SEMI "%02X" HWA_SEMI "%02X", hwa[0], hwa[1], hwa[2], hwa[3], hwa[4], hwa[5]);
    MSGraw(ANSI_COLOR_RESET "\r\n\n");
    return 0;
}

CMD_FUNCTION(read_all_phy_regs) {
    phy_read_all_regs();
    return 0;
}

CMD_FUNCTION(read_phy_reg) {
    const char *strAddr = ppArgs[0];
    uint32_t addr = strtol(strAddr, NULL, 0);
    uint32_t value;
    phy_read_reg(addr, &value);
    MSG("%04X: %04X\n", addr, value);
    return 0;
}

CMD_FUNCTION(write_phy_reg) {
    const char *strAddr = ppArgs[0];
    const char *strData = ppArgs[1];
    uint32_t addr = strtol(strAddr, NULL, 0);
    uint32_t data = strtol(strData, NULL, 0);
    phy_write_reg(addr, data);
    MSG("%04X: %04X\n", addr, data);
    return 0;
}

CMD_FUNCTION(print_samples) {

    return 0;
}

void cmd_init() {
    cli_register_command("osinfo \t\t\tPrint OS-related information", 1, 0, os_info);
    cli_register_command("phyinfo \t\t\tPrint Ethernet PHY information", 1, 0, phy_info);

    cli_register_command("ip \t\t\tPrint IP-address", 1, 0, print_ip);
    cli_register_command("hwa \t\t\tPrint hardware address", 1, 0, print_hwa);

    cli_register_command("phy readall \t\t\tRead all PHY registers", 2, 0, read_all_phy_regs);
    cli_register_command("phy read <address>\t\t\tRead a single PHY register", 2, 1, read_phy_reg);
    cli_register_command("phy write <address> <data>\t\t\tWrite a single PHY register", 2, 2, write_phy_reg);

    cli_register_command("samples \t\t\tPrint filtered samples", 1, 0, print_samples);
}