#include "SHAL.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char UARTRxBytes[60];
int curr_uart_char = 0;

void UARTCommandHandler(const char* string);

extern "C" void USART3_IRQHandler(void)
{
    // Check RXNE flag (receive register not empty)

    if (USART3->ISR & USART_ISR_RXNE_RXFNE)
    {
        auto byte = static_cast<uint8_t>((USART3->RDR & 0xFF));


        if (byte == '\r' || byte == '\n'){ //Enter case
            SHAL_UART3.sendString("\r\n");

            UARTCommandHandler(UARTRxBytes);

            for (char & UARTRxByte : UARTRxBytes) { //Clear array
                UARTRxByte = 0;
            }
            curr_uart_char = 0;
        }

        else if (byte == 0x7F || byte == 0x08){ //Backspace case
            if (curr_uart_char > 0) {
                UARTRxBytes[--curr_uart_char] = 0;
                SHAL_UART3.sendChar(0x08);  //Move cursor back
                SHAL_UART3.sendChar(' ');   //Send space
                SHAL_UART3.sendChar(0x08);  //Move cursor back
            }
        }


        else {
            SHAL_UART3.sendChar(byte);
            UARTRxBytes[curr_uart_char] = byte;
            curr_uart_char++;
        }
    }
}

struct timerInfo {
    const char* name{};
    Timer timer;
};

struct gpioTimerMap {
    GPIO_Key key;
    const char* timerName;
    SHAL_Timer_Channel channel;
    GPIO_Alternate_Function af;
};

struct adcMap {
    GPIO_Key key;
    SHAL_ADC_Channel channel;
};

constexpr int NUM_TIMERS = 14;

const timerInfo timers[NUM_TIMERS] = {
    {"TIM1", SHAL_TIM1},
    {"TIM2", SHAL_TIM2},
    {"TIM3", SHAL_TIM3},
    {"TIM4", SHAL_TIM4},
    {"TIM5", SHAL_TIM5},
    {"TIM6", SHAL_TIM6},
    {"TIM7", SHAL_TIM7},
    {"TIM8", SHAL_TIM8},
    {"TIM12", SHAL_TIM12},
    {"TIM13", SHAL_TIM13},
    {"TIM14", SHAL_TIM14},
    {"TIM15", SHAL_TIM15},
    {"TIM16", SHAL_TIM16},
    {"TIM17", SHAL_TIM17},
};

#include "User_Config.h"

void UARTCommandHandler(const char* string)
{
    char words[10][12];   //10 words max, 6 chars + null terminator
    int curr_word = 0;
    int curr_char = 0;

    for (size_t i = 0; i < 60 && curr_word < 10; i++)
    {
        char c = string[i];

        if (c == ' ' || c == '\0')
        {
            if (curr_char > 0)  // Ignore multiple spaces
            {
                words[curr_word][curr_char] = '\0';  // Null terminate
                curr_word++;
                curr_char = 0;  // Reset for next word
            }

            if (c == '\0') break;  //End of string
        }
        else if (curr_char < 11)
        {
            words[curr_word][curr_char++] = c;
        }
    }

    if (words[0][0] == 'P') { //Pin starts with P
        //Check for valid pin
        const uint8_t portNum = static_cast<uint8_t>(words[0][1]) - 'A'; //Port number
        const auto pinNum = atoi((words[0] + 2)); //Pin number

        if ((portNum < AVAILABLE_PORTS - 1) && (pinNum < PINS_PER_PORT)) { //Valid pin

            auto pin = GPIOManager::get(portNum,pinNum); //Get GPIO pin

            if (strcmp(words[1], "SET") == 0) { //SET ------------------------------------------

                if (curr_word < 3) return; //No subcommand, seg fault

                pin.setPinMode(PinMode::OUTPUT_MODE);

                if (strcmp(words[2], "HIGH") == 0) { //GPIO toggle
                    pin.setHigh();
                }
                else if (strcmp(words[2], "LOW") == 0) {
                    pin.setLow();
                }
            }
            else if (strcmp(words[1], "TOG") == 0) { //TOGGLE ------------------------------------------
                pin.setPinMode(PinMode::OUTPUT_MODE);
                pin.toggle();
            }
            else if (strcmp(words[1], "READ") == 0) { //TOGGLE ------------------------------------------
                pin.setPinMode(PinMode::INPUT_MODE);

                SHAL_delay_us(10);

                const uint16_t val = pin.digitalRead();
                char buff[8];
                snprintf(buff, 8, "%d\r\n", val);
                SHAL_UART3.sendString(buff);
            }
            else if (strcmp(words[1], "ADC") == 0) { //ADC READ -------------------------------------------
                pin.setPinMode(PinMode::ANALOG_MODE);

                SHAL_ADC_Channel channel;
                bool found = false;

                for (adcMap map : adcInfo) {
                    if (pin.getKey() == map.key) {
                        channel = map.channel;
                        found = true;
                    }
                }

                if (!found) {
                    SHAL_UART3.sendString("INVALID ADC\r\n");
                    return;
                }

                const auto res = SHAL_ADC1.singleConvertSingle(channel, SHAL_ADC_SampleTime::C8);

                char buff[32];
                uint32_t millivolts = ((uint32_t)res * 3300) / 65535;
                snprintf(buff, sizeof(buff), "%lu.%03lu V\r\n", millivolts / 1000, millivolts % 1000);
                SHAL_UART3.sendString(buff);
            }
        }else {
            SHAL_UART3.sendString("INVALID PIN");
        }
    }
    else if (strncmp(words[0],"TIM",3) == 0) { //Timer control ---------------------------------------------
        const char* timNumStr = words[0];
        int timerNum = 0;
        bool validTimer = false;

        for (int i = 0; i < NUM_TIMERS; i++) { //Num timers
            if (strcmp(timers[i].name,timNumStr) == 0) {
                validTimer = true;
                timerNum = i;
                break;
            }
        }

        if (!validTimer) {
            SHAL_UART3.sendString("INVALID TIMER\r\n");
            return;
        }

        Timer currTimer = timers[timerNum].timer; //get our timer

        if (strcmp(words[1], "START") == 0) { //SET ------------------------------------------
            currTimer.init();

            currTimer.start();

            SHAL_UART3.sendString("Started timer\r\n");
        }
        else if (strcmp(words[1], "STOP") == 0) {
            currTimer.stop();
            SHAL_UART3.sendString("Stopped timer\r\n");

        }
        else if (strncmp(words[1], "CH",2) == 0) { //Channel selection

            int channelNum = atoi((words[1] + 2));
            auto timerChannel = static_cast<SHAL_Timer_Channel>(channelNum);

            if (strcmp(words[2], "PWM") == 0) {
                currTimer.stop();

                for (int i = 0; i < NUM_TIMER_GPIOS; i++) {
                    if (strcmp(gpioTimerInfo[i].timerName,words[0]) == 0) {
                        if (gpioTimerInfo[i].channel == timerChannel) {

                            auto gpio_key = gpioTimerInfo[i].key;
                            auto gpio = GPIOManager::get(gpio_key);

                            gpio.setPinMode(PinMode::ALTERNATE_FUNCTION_MODE);
                            gpio.setAlternateFunction(gpioTimerInfo[i].af);

                            break;

                        }
                    }
                }

                const uint32_t psc = atoi(words[3]);
                const uint32_t arr = atoi(words[4]);
                const uint32_t cc = atoi(words[5]);

                currTimer.init();

                currTimer.configurePWM(timerChannel,psc,arr,cc);

                currTimer.start();
            }
        }
        else {
            SHAL_UART3.sendString("BAD TIM COMMAND\r\n");
            return;
        }
    }
}


int main() {

    SHAL_init();

    NVIC_SetPriority(USART3_IRQn, 1); //Enable UART interrupts
    NVIC_EnableIRQ(USART3_IRQn);

    SHAL_UART3.init(UART_Pair_Key::Tx3D8_Rx3D9);
    SHAL_UART3.begin(115200,SHAL_USART_Word_Length::Bits_8);

    SHAL_ADC1.init(ADC_Key::S_ADC1, SHAL_ADC_Sample_Mode::SINGLE_ENDED);

    for (const adcMap map : adcInfo) {
        SHAL_ADC1.preselectChannel(map.channel);
    }

    while (true) {

    }
}