#include "led.h"
#include <zephyr/sys/printk.h>

/* Device tree bindings */
#define LED0_NODE DT_ALIAS(led0)
#define LED1_NODE DT_ALIAS(led1)

static const struct gpio_dt_spec led0 = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
static const struct gpio_dt_spec led1 = GPIO_DT_SPEC_GET(LED1_NODE, gpios);

static struct k_timer led0_timer;
static struct k_timer led1_timer;

static void led0_timer_handler(struct k_timer *dummy) { gpio_pin_toggle_dt(&led0); }
static void led1_timer_handler(struct k_timer *dummy) { gpio_pin_toggle_dt(&led1); }

void led_init(void) {
    if (!device_is_ready(led0.port) || !device_is_ready(led1.port)) {
        printk("LED devices not ready\n");
        return;
    }
    gpio_pin_configure_dt(&led0, GPIO_OUTPUT_INACTIVE);
    gpio_pin_configure_dt(&led1, GPIO_OUTPUT_INACTIVE);
    k_timer_init(&led0_timer, led0_timer_handler, NULL);
    k_timer_init(&led1_timer, led1_timer_handler, NULL);
}

void led_set(int led_id, int state) {
    if (led_id == 0) gpio_pin_set_dt(&led0, state);
    else if (led_id == 1) gpio_pin_set_dt(&led1, state);
}

void led_toggle(int led_id) {
    if (led_id == 0) gpio_pin_toggle_dt(&led0);
    else if (led_id == 1) gpio_pin_toggle_dt(&led1);
}

void led_start_blink(int led_id, int interval_ms) {
    if (led_id == 0) k_timer_start(&led0_timer, K_MSEC(interval_ms), K_MSEC(interval_ms));
    else if (led_id == 1) k_timer_start(&led1_timer, K_MSEC(interval_ms), K_MSEC(interval_ms));
}

void led_stop_blink(int led_id) {
    if (led_id == 0) k_timer_stop(&led0_timer);
    else if (led_id == 1) k_timer_stop(&led1_timer);
}
