#include "uart.h"
#include "gd32e23x_usart.h"
#include "gd32e23x_rcu.h"
#include "gd32e23x_gpio.h"


void uart0_init(uint32_t baudrate) {
    /* 使能 GPIOA 和 USART0 时钟 */
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_USART0);

    /* 配置 PA9 为 USART0_TX，PA10 为 USART0_RX */
    gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_9 | GPIO_PIN_10);
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_9 | GPIO_PIN_10);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9 | GPIO_PIN_10);

    /* 配置波特率、数据位、停止位等 */
    usart_deinit(USART0);
    usart_baudrate_set(USART0, baudrate);
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);
    usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
    usart_enable(USART0);
}

void uart1_init(uint32_t baudrate) {
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_USART1);
    // USART1 默认引脚为 PA2 (TX), PA3 (RX)
    gpio_af_set(GPIOA, GPIO_AF_1, GPIO_PIN_2 | GPIO_PIN_3);
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_2 | GPIO_PIN_3);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_2 | GPIO_PIN_3);
    usart_deinit(USART1);
    usart_baudrate_set(USART1, baudrate);
    usart_receive_config(USART1, USART_RECEIVE_ENABLE);
    usart_transmit_config(USART1, USART_TRANSMIT_ENABLE);
    usart_enable(USART1);
}

static uart_printf_port_t g_printf_port = UART_PRINTF_USART0;

void uart_set_printf_port(uart_printf_port_t port) {
    g_printf_port = port;
}

// printf 重定向，支持多串口
int __io_putchar(int ch) {
    switch (g_printf_port) {
        case UART_PRINTF_USART0:
            while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET) {}
            usart_data_transmit(USART0, (uint8_t)ch);
            break;
        case UART_PRINTF_USART1:
            while (usart_flag_get(USART1, USART_FLAG_TBE) == RESET) {}
            usart_data_transmit(USART1, (uint8_t)ch);
            break;
        case UART_PRINTF_BOTH:
            while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET) {}
            usart_data_transmit(USART0, (uint8_t)ch);
            while (usart_flag_get(USART1, USART_FLAG_TBE) == RESET) {}
            usart_data_transmit(USART1, (uint8_t)ch);
            break;
        default:
            break;
    }
    return ch;
}
