#include "usart.h"
#include <string.h>
#include "cmd.h"
#include "log.h"
#include "main.h"
#include "dma.h"
#include <stdint.h>
#include "stm32l4xx_hal_uart.h"
#include "flash.h"
#include <stdio.h>

uint8_t cmdData[32];
uint8_t uart1len = 0;
uint8_t g_debugLevel = 0;
uint8_t g_direction = 0;
extern DMA_HandleTypeDef hdma_usart1_rx;

FlashConfig_t *currentConfig;


void UART_CommandHandler(char *data, uint16_t len)
{
    data[len] = '\0';  // 确保字符串结束

    if (strncmp(data, "SETID", 5) == 0)
    {
        uint8_t id;
        if (sscanf(data + 5, "%x", &id) == 1)
        {
            
            currentConfig = Flash_ReadConfig();
            if(currentConfig->can_id != id)
            {
                _dbg_printf("Current ID: 0x%02X, New ID: 0x%02X\n", currentConfig->can_id, id);
                currentConfig->can_id = id;
                currentConfig->crc = id ^ 0xFF; // 简单校验
                Flash_WriteConfig(currentConfig);
            }
            else
            {
                _dbg_printf("CAN ID unchanged: 0x%02X\n", id);
            }
            
        }
    }
    else if(strncmp(data, "SETDEBUG", 8) == 0)
    {
        uint8_t debug;
        if (sscanf(data + 8, "%x", &debug) == 1)
        {
            g_debugLevel = debug;
            _dbg_printf("Set debug level: 0x%02X\n", g_debugLevel);
        }
    }
    else if(strncmp(data, "SETDIR", 6) == 0)
    {
        uint8_t dir;
        if (sscanf(data + 6, "%x", &dir) == 1)
        {
            g_direction = dir;
            _dbg_printf("Set direction: 0x%02X\n", g_direction);
        }
    }
    else
    {
        _dbg_printf("Unknown command: %s\n", data);
    }
}


void init_cmd(void)
{
    __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
    __HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
    HAL_UART_Receive_DMA(&huart1, cmdData, sizeof(cmdData));
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        HAL_UART_DMAStop(huart);
        uart1len = 0;
        memset(cmdData, 0, sizeof(cmdData));
        HAL_UART_Receive_DMA(huart, cmdData, sizeof(cmdData));
    }
}

void usart_irq_dma_process(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET)
        {
            __HAL_UART_CLEAR_IDLEFLAG(huart);
            HAL_UART_DMAStop(huart);
            uart1len = sizeof(cmdData) - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
            UART_CommandHandler((char *)cmdData, uart1len);
            memset(cmdData, 0, sizeof(cmdData));
            HAL_UART_Receive_DMA(huart, cmdData, sizeof(cmdData));
        }
    }
}
