#include "uart.h"
#include "os/os_task.h"
#include "libs/crc16.h"
#include "libs/logger.h"
#include "libs/utils.h"

#define SHARK_UART_BAUDRATE				230400

#ifdef DEBUG_PORT_UART1
#define SHARK_UART0_com					USART1
#define SHARK_UART0_tx_port				GPIOA
#define SHARK_UART0_tx_pin				GPIO_PIN_2
#define SHARK_UART0_rx_port				GPIOA
#define SHARK_UART0_rx_pin				GPIO_PIN_3
#define SHARK_UART0_irq					USART1_IRQn
#define SHARK_UART0_clk					RCU_USART1
#define SHARK_UART0_tx_gpio_clk			RCU_GPIOA
#define SHARK_UART0_rx_gpio_clk			RCU_GPIOA
#define SHARK_UART0_tx_dma				DMA0
#define SHARK_UART0_tx_dma_ch			DMA_CH6
#define SHARK_UART0_tx_dma_clk			RCU_DMA0
#define SHARK_UART0_rx_dma				DMA0
#define SHARK_UART0_rx_dma_ch			DMA_CH5
#define SHARK_UART0_rx_dma_clk			RCU_DMA0
#define SHARK_UART0_DMA_TX_IRQ          DMA0_Channel6_IRQn
#define UART_DMA_IRQHandler             DMA0_Channel6_IRQHandler
#else
#define SHARK_UART0_com					USART3
#define SHARK_UART0_tx_port				GPIOB
#define SHARK_UART0_tx_pin				GPIO_PIN_10
#define SHARK_UART0_rx_port				GPIOB
#define SHARK_UART0_rx_pin				GPIO_PIN_11
#define SHARK_UART0_irq					USART3_IRQn
#define SHARK_UART0_clk					RCC_APB1_PERIPH_USART3
#define SHARK_UART0_tx_gpio_clk			RCC_APB2_PERIPH_GPIOB
#define SHARK_UART0_rx_gpio_clk			RCC_APB2_PERIPH_GPIOB
#define SHARK_UART0_tx_dma				DMA1
#define SHARK_UART0_tx_dma_ch			DMA1_CH2
#define SHARK_UART0_tx_dma_clk			RCC_AHB_PERIPH_DMA1
#define SHARK_UART0_rx_dma				DMA0
#define SHARK_UART0_rx_dma_ch			DMA1_CH3
#define SHARK_UART0_rx_dma_clk			RCC_AHB_PERIPH_DMA1
#define SHARK_UART0_DMA_TX_IRQ          DMA0_Channel1_IRQn

#define USARTy_Tx_DMA_FLAG    DMA1_FLAG_TC2
#define USARTy_Rx_DMA_FLAG    DMA1_FLAG_TC3

#define UART_DMA_IRQHandler             DMA0_Channel1_IRQHandler
#endif

// ================================================================================
#define ENABLE_RX_DMA 1
static u8 shark_uart0_tx_cache[SHARK_UART_TX_MEM_SIZE];
static u8 shark_uart0_rx_cache[SHARK_UART_RX_MEM_SIZE];

static shark_uart_t _shark_uart[1];
///static bool uart_no_data = false;
#if ENABLE_RX_DMA==1
#define update_dma_w_pos(uart) circle_update_write_position(&uart->rx_queue, SHARK_UART_RX_MEM_SIZE - DMA_GetCurrDataCounter(SHARK_UART0_rx_dma_ch))
#else
#define update_dma_w_pos(uart){}
#endif

// ================================================================================

static bool shark_uart_on_rx_frame(shark_uart_t *uart)
{
	u16 crc0 = decode_u16(uart->rx_frame + uart->rx_length);
	u16 crc1 = crc16_get(uart->rx_frame, uart->rx_length);

	if (crc0 != crc1) {
		return false;
	}
	//protocol_recv_frame(_uart_index(uart->uart_com), (char *)uart->rx_frame, uart->rx_length);
	return true;
}

static void shark_uart_rx(shark_uart_t *uart){
	while(1) {
		u8 data = 0;
		update_dma_w_pos(uart);
		if (circle_get_one_data(&uart->rx_queue, &data) != 1) {
			return;
		}
		switch(data){
			case CH_START:
				uart->rx_length = 0;
				uart->escape = false;
				uart->start = true;
				break;
			case CH_END:
				if (uart->rx_length > 2 && uart->rx_length != 0xFFFF){
					uart->rx_length -= 2; //skip crc
					shark_uart_on_rx_frame(uart);
				}
				uart->rx_length = 0xFFFF;
				uart->start = false;
				break;
			case CH_ESC:
				uart->escape = true;
				break;
			default:
				if (uart->escape) {
					uart->escape = false;
					switch (data) {
						case CH_ESC_START:
							data = CH_START;
							break;

						case CH_ESC_END:
							data = CH_END;
							break;

						case CH_ESC_ESC:
							data = CH_ESC;
							break;

						default:
							data = 0xFF;
					}
				}

				if (uart->rx_length < sizeof(uart->rx_frame)) {
					uart->rx_frame[uart->rx_length] = data;
					uart->rx_length++;
				} else {
					uart->rx_length = 0xFFFF;
				}			
		}
	}
}

#define DMA_CHCTL(SHARK_UART0_tx_dma, tx_dma_ch)   (tx_dma_ch->CHCFG)
static void shark_uart_dma_tx(shark_uart_t *uart)
{
	u32 value = DMA_CHCTL(SHARK_UART0_tx_dma, uart->tx_dma_ch);

	if (value & DMA_CHCFG1_CHEN) {
		if (SET != DMA_GetFlagStatus(USARTy_Tx_DMA_FLAG, SHARK_UART0_tx_dma)) {
			return;
		}
		DMA_ClearFlag(USARTy_Tx_DMA_FLAG, SHARK_UART0_tx_dma);
		byte_queue_skip(&uart->tx_queue, uart->tx_length);
		DMA_CHCTL(SHARK_UART0_tx_dma, uart->tx_dma_ch) = value & (~DMA_CHCFG1_CHEN);
	}

	uart->tx_length = byte_queue_peek(&uart->tx_queue);
	if (uart->tx_length > 0) {
		DMA_SetCurrDataCounter(uart->tx_dma_ch, uart->tx_length);
		uart->tx_dma_ch->MADDR = (u32) byte_queue_head(&uart->tx_queue);
		DMA_CHCTL(SHARK_UART0_tx_dma, uart->tx_dma_ch) = value | DMA_CHCFG1_CHEN;
	}
}



static void shark_uart_write(shark_uart_t *uart, const u8 *buff, u16 size)
{
	while (size > 0) {
		u16 length = byte_queue_write(&uart->tx_queue, buff, size);

		if (length == size) {
			shark_uart_dma_tx(uart);
			break;
		}

		shark_uart_dma_tx(uart);
		buff += length;
		size -= length;
	}
}

static void shark_uart_write_byte(shark_uart_t *uart, u8 value)
{
	byte_queue_write(&uart->tx_queue, &value, 1);
}


void shark_uart_write_log(char *buffer){
	int len = strlen(buffer);
	shark_uart_t *uart = (_shark_uart+SHARK_UART0);
	if (len > byte_queue_get_free(&uart->tx_queue)){
		return;
	}
	byte_queue_write(&uart->tx_queue, (const u8 *)buffer, len);
	shark_uart_dma_tx(uart);
}

static void shark_uart_tx_dma_init(shark_uart_t *uart){

	rcu_ahb_periph_clock_enable(SHARK_UART0_tx_dma_clk);

    DMA_InitType DMA_InitStructure;

    /* USARTy TX DMA1 Channel (triggered by USARTy Tx event) Config */
    DMA_DeInit(SHARK_UART0_tx_dma_ch);
    DMA_InitStructure.PeriphAddr     = (u32)uart->uart_com + 0x04;
    DMA_InitStructure.Direction      = DMA_DIR_PERIPH_DST;
    DMA_InitStructure.BufSize        = 0;
    DMA_InitStructure.PeriphInc      = DMA_PERIPH_INC_DISABLE;
    DMA_InitStructure.DMA_MemoryInc  = DMA_MEM_INC_ENABLE;
    DMA_InitStructure.PeriphDataSize = DMA_PERIPH_DATA_SIZE_BYTE;
    DMA_InitStructure.MemDataSize    = DMA_MemoryDataSize_Byte;
    DMA_InitStructure.CircularMode   = DMA_MODE_NORMAL;
    DMA_InitStructure.Priority       = DMA_PRIORITY_VERY_HIGH;
    DMA_InitStructure.Mem2Mem        = DMA_M2M_DISABLE;
    DMA_Init(SHARK_UART0_tx_dma_ch, &DMA_InitStructure);

	USART_EnableDMA(uart->uart_com, USART_DMAREQ_TX, ENABLE);
}

#if ENABLE_RX_DMA==1
static void shark_uart_rx_dma_init(shark_uart_t *uart){

	rcu_ahb_periph_clock_enable(SHARK_UART0_rx_dma_clk);

    DMA_InitType DMA_InitStructure;

    /* USARTy TX DMA1 Channel (triggered by USARTy Tx event) Config */
    DMA_DeInit(SHARK_UART0_rx_dma_ch);
    DMA_InitStructure.PeriphAddr     = (u32)uart->uart_com + 0x04;
    DMA_InitStructure.Direction      = DMA_DIR_PERIPH_SRC;
    DMA_InitStructure.BufSize        = uart->rx_queue.buffer_len;
	DMA_InitStructure.MemAddr        = (u32)uart->rx_queue.buffer;
    DMA_InitStructure.PeriphInc      = DMA_PERIPH_INC_DISABLE;
    DMA_InitStructure.DMA_MemoryInc  = DMA_MEM_INC_ENABLE;
    DMA_InitStructure.PeriphDataSize = DMA_PERIPH_DATA_SIZE_BYTE;
    DMA_InitStructure.MemDataSize    = DMA_MemoryDataSize_Byte;
    DMA_InitStructure.CircularMode   = DMA_MODE_CIRCULAR;
    DMA_InitStructure.Priority       = DMA_PRIORITY_VERY_HIGH;
    DMA_InitStructure.Mem2Mem        = DMA_M2M_DISABLE;
    DMA_Init(SHARK_UART0_rx_dma_ch, &DMA_InitStructure);

	USART_EnableDMA(uart->uart_com, USART_DMAREQ_RX, ENABLE);

}
#endif
static void shark_uart_pin_init(shark_uart_t *uart){
	rcu_apb1_periph_clock_enable(SHARK_UART0_clk);
	rcu_apb2_periph_clock_enable(SHARK_UART0_rx_gpio_clk);
	rcu_apb2_periph_clock_enable(SHARK_UART0_tx_gpio_clk);
	rcu_apb2_periph_clock_enable(RCU_AF);
	gpio_init(SHARK_UART0_tx_port, GPIO_MODE_AF_PP,GPIO_OSPEED_50MHZ,SHARK_UART0_tx_pin);
	gpio_init(SHARK_UART0_rx_port, GPIO_MODE_IN_FLOATING,GPIO_OSPEED_50MHZ,SHARK_UART0_rx_pin);
}


static void shark_uart_device_init(shark_uart_t *uart){
	USART_InitType USART_InitStructure;

	USART_StructInit(&USART_InitStructure);
    USART_InitStructure.BaudRate            = SHARK_UART_BAUDRATE;
    USART_InitStructure.WordLength          = USART_WL_8B;
    USART_InitStructure.StopBits            = USART_STPB_1;
    USART_InitStructure.Parity              = USART_PE_NO;
    USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
    USART_InitStructure.Mode                = USART_MODE_RX | USART_MODE_TX;
	/* Configure USARTy and USARTz */
	USART_Init(uart->uart_com, &USART_InitStructure);

	USART_Enable(uart->uart_com, ENABLE);
}

static u32 shark_uart_task(void *args)
{
	shark_uart_t *uart = (shark_uart_t *)args;
	if(uart->uart_com != 0) {
		shark_uart_rx(uart);
		shark_uart_dma_tx(uart);
	}
	return 0;
}


void shark_uart_flush(void){
	shark_uart_t *uart = _shark_uart + SHARK_UART0;
	if (uart->uart_com != 0) {
		while(!byte_queue_empty(&uart->tx_queue)) {
			shark_uart_dma_tx(uart);
		}
	}	
}

static u8 *tx_cache_addr(uart_enum_t uart_no){
	return shark_uart0_tx_cache;
}

static u8 *rx_cache_addr(uart_enum_t uart_no){
	return shark_uart0_rx_cache;
}


void shark_uart_deinit(uart_enum_t uart_no){

}


bool shark_uart_timeout(void){
#if UART_NUM==2	
	return (_shark_uart[0].uart_no_data && _shark_uart[1].uart_no_data)?TRUE:FALSE;
#else
	return (_shark_uart[0].uart_no_data)?TRUE:FALSE;
#endif
}
void shark_uart_init(uart_enum_t uart_no)
{
	shark_uart_t *uart = _shark_uart + uart_no;
	uart->escape = false;
	uart->rx_length = 0;
	uart->tx_length = 0;
	uart->uart_com = SHARK_UART0_com;

	circle_buffer_init(&uart->rx_queue, rx_cache_addr(uart_no), SHARK_UART_RX_MEM_SIZE);
	byte_queue_init(&uart->tx_queue,tx_cache_addr(uart_no), SHARK_UART_TX_MEM_SIZE);

	uart->rx_dma_ch = SHARK_UART0_rx_dma_ch;
	uart->tx_dma_ch = SHARK_UART0_tx_dma_ch;

	shark_uart_pin_init(uart);
	shark_uart_device_init(uart);
	shark_uart_rx_dma_init(uart);
	shark_uart_tx_dma_init(uart);

	shark_task_create(shark_uart_task, uart);

	uart->uart_no_data = false;
}

void UART_DMA_IRQHandler(void) {
	
}

static void shark_uart_write_byte_esc(shark_uart_t *uart, u8 value)
{
	switch (value) {
	case CH_START:
		shark_uart_write_byte(uart, CH_ESC);
		value = CH_ESC_START;
		break;

	case CH_END:
		shark_uart_write_byte(uart, CH_ESC);
		value = CH_ESC_END;
		break;

	case CH_ESC:
		shark_uart_write_byte(uart, CH_ESC);
		value = CH_ESC_ESC;
		break;
	}

	shark_uart_write_byte(uart, value);
}

static void shark_uart_write_esc(shark_uart_t *uart, const u8 *buff, u16 length)
{
	const u8 *buff_end;

	for (buff_end = buff + length; buff < buff_end; buff++) {
		shark_uart_write_byte_esc(uart, *buff);
	}
}

static void shark_uart_tx_start(shark_uart_t *uart)
{
	shark_uart_write_byte(uart, CH_START);
	uart->tx_crc16 = 0;
}

static void shark_uart_tx_continue(shark_uart_t *uart, const void *buff, u16 length)
{
	shark_uart_write_esc(uart, (const u8 *) buff, length);
	uart->tx_crc16 = crc16_update(uart->tx_crc16, (const u8 *) buff, length);
}

static void shark_uart_tx_end(shark_uart_t *uart)
{
	shark_uart_write_esc(uart, (u8 *)&uart->tx_crc16, sizeof(uart->tx_crc16));
	shark_uart_write_byte(uart, CH_END);
}

void shark_uart_write_frame(uart_enum_t uart_no, uint8_t *bytes, int len){
	shark_uart_t *uart = _shark_uart + uart_no;
	shark_uart_tx_start(uart);
	shark_uart_tx_continue(uart, bytes, len);
	shark_uart_tx_end(uart);
	shark_uart_dma_tx(uart);
}

void shark_uart_frame_start(uart_enum_t uart_no, uint8_t *bytes, int len){
	shark_uart_t *uart = _shark_uart + uart_no;
	shark_uart_tx_start(uart);
	shark_uart_tx_continue(uart, bytes, len);
}

void shark_uart_frame_continue(uart_enum_t uart_no, uint8_t *bytes, int len){
	shark_uart_t *uart = _shark_uart + uart_no;
	shark_uart_tx_continue(uart, bytes, len);
}

void shark_uart_frame_end(uart_enum_t uart_no){
	shark_uart_tx_end(_shark_uart + uart_no);
}

void shark_uart_write_bytes(uart_enum_t uart_no, u8 *buff, u16 size){
	shark_uart_write(_shark_uart + uart_no, buff, size);
}

int fputc(int c, FILE *fp){
	shark_uart_write_byte(_shark_uart+SHARK_UART0, (u8)c);
	return 1;
}

