#include "usb_api.h"
#include <string.h>
#include "esp_err.h"
#include "esp_log.h"
#include "driver/usb_serial_jtag.h"

static const char *TAG = "usb_api";
static usb_api_line_handler_t s_handler = NULL;
static char s_line_buf[256];
static size_t s_line_len = 0;

void usb_api_init(usb_api_line_handler_t handler)
{
    s_handler = handler;
    s_line_len = 0;
    usb_serial_jtag_driver_config_t cfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT();
    esp_err_t err = usb_serial_jtag_driver_install(&cfg);
    if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
        ESP_LOGE(TAG, "usb driver install failed: %s", esp_err_to_name(err));
    }
}

bool usb_api_is_connected(void)
{
    return usb_serial_jtag_is_connected();
}

void usb_api_send_line(const char *line)
{
    if (!line) {
        return;
    }
    size_t len = strlen(line);
    if (len == 0) {
        return;
    }
    int written = usb_serial_jtag_write_bytes((const uint8_t *)line, len, 0);
    if (written < 0) {
        ESP_LOGW(TAG, "usb write failed");
    }
}

static void handle_complete_line(void)
{
    if (s_line_len == 0) {
        return;
    }
    s_line_buf[s_line_len] = '\0';
    if (s_handler) {
        s_handler(s_line_buf);
    }
    s_line_len = 0;
}

void usb_api_tick(void)
{
    uint8_t buf[64];
    int n = usb_serial_jtag_read_bytes(buf, sizeof(buf), 0);
    if (n <= 0) {
        return;
    }
    for (int i = 0; i < n; i++) {
        char c = (char)buf[i];
        if (c == '\r' || c == '\n') {
            handle_complete_line();
            continue;
        }
        if (s_line_len + 1 >= sizeof(s_line_buf)) {
            // drop line on overflow
            s_line_len = 0;
            continue;
        }
        s_line_buf[s_line_len++] = c;
    }
}
