#include "com_uart.h"


#define MODULE COM_UART
LOG_MODULE_REGISTER(MODULE);

static const struct device *com_uart1 = DEVICE_DT_GET(DT_NODELABEL(uart1));
//static const struct device *com_uart1 = NULL;

static bool rx_throttled;
bool flag_message_received;
size_t index_buf_rx;
uint8_t buf_rx[1500];

static void com_uart1_cb(const struct device *dev, void *user_data)
{
	ARG_UNUSED(user_data);

    uint8_t c;

	while (uart_irq_update(dev) && uart_irq_is_pending(dev)) {

		if (uart_irq_rx_ready(dev)) {
			uart_fifo_read(dev, &c, 1);
			buf_rx[index_buf_rx++] = c;

			if(buf_rx[index_buf_rx-2] == '\r'
			&& buf_rx[index_buf_rx-1] == '\n')
			{
				if(index_buf_rx > 0)
				{
					buf_rx[index_buf_rx-2] = '\0';
					buf_rx[index_buf_rx-1] = '\0';

					flag_message_received = true;
					LOG_INF("Meesage recu");
				}
			}
		}

		/*if (uart_irq_tx_ready(dev)) {

            if (!ring_buf_is_empty(&ring_buf_tx))
            {
                uint8_t *data;
                
                // Get buffer within a ring buffer memory.
                uint32_t size = ring_buf_get_claim(&ring_buf_tx, &data, ring_buf_size_get(&ring_buf_tx));

                uint32_t written = 0;
                while (size > written) {
                    written += uart_fifo_fill(dev,
                        &data[written],
                        size - written);
                    while (!uart_irq_tx_complete(dev)) {
                        // Wait for the last byte to get
                        // shifted out of the module
                    }
                }
                
                ring_buf_get_finish(&ring_buf_tx, size);
                
                if (ring_buf_is_empty(&ring_buf_tx))
                {
                    uart_irq_tx_disable(dev);
                }	
            }	
		}*/
	}
}

void com_uart1_clean_rx_buffer(void)
{
    index_buf_rx = 0;
	memset(buf_rx, 0x00, sizeof(buf_rx));
    //ring_buf_reset(&ring_buf_rx);
}

void com_uart1_send_data(char *message, size_t len)
{		
	
	for (int i = 0; i < len; i++)
	{
		uart_poll_out(com_uart1, message[i]);
	}
	
	uart_poll_out(com_uart1, '\r');
	uart_poll_out(com_uart1, '\n');
}

int com_uart1_init(void)
{
	int ret;

    if (!device_is_ready(com_uart1)) {
		LOG_ERR("Error: Device \"%s\" is not ready; "
				"check the driver initialization logs for errors.",
			com_uart1->name);
		return -ENODEV;
	}

    flag_message_received = false;

	uart_irq_rx_disable(com_uart1);
	uart_irq_tx_disable(com_uart1);

    //uart_irq_callback_set(com_uart1, interrupt_handler);
	ret = uart_irq_callback_user_data_set(com_uart1, com_uart1_cb, NULL);
	if(ret < 0)
	{
		if(ret == -ENOTSUP)
		{
			LOG_ERR("Interrupt-driven UART API support not enable");
		}
		else if (ret == -ENOSYS)
		{
			LOG_ERR("UART device does not support interrupt-driven API");
		}
		else 
		{
			LOG_ERR("Error setting UART callback : %d", ret);
		}
	}

	/* Enable rx interrupts */
	uart_irq_rx_enable(com_uart1);

	return 0;
}

