/*
 * ll_testbed.cpp
 *
 *  Created on: Oct 28, 2019
 *      Author: abody
 */
#include <main.h>
#include <projdefs.h>

#include <cmsis_os.h>

#include <FreeRTOS.h>
#include <task.h>

#include <f4ll/console_handler.h>
#include <f4ll/str_util.h>

#include <stdlib.h>
#include <string.h>

#include <app.h>

void app_main(void const *param)
{

    app::init(param).main();
}

app::app(void const *param)
    : m_con(
          f4ll::console_handler::init(
              USART2, DMA1, LL_DMA_STREAM_5, LL_DMA_STREAM_6, m_rx_buf_mem, sizeof(m_rx_buf_mem), m_tx_buf_mem, sizeof(m_tx_buf_mem),
              nullptr)),
      m_safe_conout(m_con)

{
    (void)param;
}

void app::main()
{
    m_cli_task_handle = xTaskCreateStatic(
        cli_task_dispatch, "CLI_task", CLI_TASK_STACK_LEN, this, osPriorityAboveNormal, m_cli_task_stack, &m_cli_task_buffer);

    queue_ts();
    m_safe_conout.print("-------------------------------------------\n");
    while (true) {
        // queue_ts();
        // m_safe_conout.print("Hello woooooooooooooooooooooooooooooooorld!\n");
        vTaskDelay(pdMS_TO_TICKS(500));
        LL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
    }
}

void app::input_available(f4ll::console_handler::size_type len)
{
    // TODO: trigger a semaphore here and do the processing from a task. This is running in interrupt context
    f4ll::iringbuffer &rb = f4ll::console_handler::instance().get_rx_buffer();
    f4ll::console_handler::size_type chunk_len = 0;
    uint8_t const *chunk = nullptr;
    bool more = false;
    do {
        more = rb.get_chunk(chunk, chunk_len);
        if (chunk_len) {
            rb.consumed(chunk_len);
        }
    } while (more);
}

void app::cli_task()
{
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(10000));
        // queue_ts();
        // m_safe_conout.print(">>> TICK <<<\n");
    }
}

void app::queue_ts()
{
    char ts_buf[12];
    uitodec(ts_buf, xTaskGetTickCount());
    m_safe_conout.append(ts_buf);
    m_safe_conout.append(" ");
}