#include "uart_driver.h"
#include <string.h>

// Mock implementation for ESP32-C6 UART driver
// In a real implementation, this would use ESP-IDF UART drivers

bool uart_driver_init(uart_driver_t *driver, const uart_config_t *config) {
    if (!driver || !config) {
        return false;
    }

    // Validate configuration
    if (config->baud_rate <= 0 ||
        (config->data_bits != 5 && config->data_bits != 6 &&
         config->data_bits != 7 && config->data_bits != 8) ||
        (config->parity < 0 || config->parity > 2) ||
        (config->stop_bits != 1 && config->stop_bits != 2)) {
        return false;
    }

    // In a real implementation, we would configure the ESP32-C6 UART peripheral here
    // For now, we'll just store the configuration and mark as initialized

    driver->uart_num = 0; // Using UART0 for simplicity
    driver->initialized = true;

    return true;
}

void uart_driver_deinit(uart_driver_t *driver) {
    if (driver) {
        driver->initialized = false;
        driver->uart_num = -1;
    }
}

bool uart_driver_send(uart_driver_t *driver, const uint8_t *data, size_t length, uint32_t timeout_ms) {
    if (!driver || !data || !driver->initialized) {
        return false;
    }

    if (length == 0) {
        return true;
    }

    // In a real implementation, we would use ESP-IDF UART write functions here
    // For now, we'll simulate successful transmission

    // Simulate sending data (in reality, this would be non-blocking or use interrupts)
    (void)timeout_ms; // Parameter not used in mock

    return true;
}

int uart_driver_receive(uart_driver_t *driver, uint8_t *data, size_t max_length, uint32_t timeout_ms) {
    if (!driver || !data || !driver->initialized) {
        return -1;
    }

    if (max_length == 0) {
        return 0;
    }

    // In a real implementation, we would use ESP-IDF UART read functions here
    // For now, we'll simulate receiving no data (timeout)

    (void)timeout_ms; // Parameter not used in mock

    // Return 0 to indicate no data received (timeout)
    return 0;
}

bool uart_driver_is_initialized(const uart_driver_t *driver) {
    if (!driver) {
        return false;
    }
    return driver->initialized;
}