#include "ws2812_spi_shell.h"
#include "ws2812_spi.h"
#include "shell/sh.h"
#include "sh_vset.h"
#include "hal/spi_types.h"

static ws2812_spi_led_buf_t *s_led_strip;
static uint32_t s_value;

SH_CMD_FN(set);
SH_CMD_FN(clr);

SH_DEF_SUB_CMD(
    sub_led,
    SH_SETUP_CMD("set", "点亮灯珠 <引脚号> <灯珠号> [红] [绿] [蓝]", set, NULL), //
    SH_SETUP_CMD("clr", "熄灭全部灯珠 <引脚号>", clr, NULL),                     //
);

SH_DEF_CMD(
    _register_cmd,
    SH_SETUP_CMD("led", "操作灯带驱动", NULL, sub_led), //
);

void ws2812_spi_shell_register(void)
{
#if defined(CONFIG_LED_STRIP_MAX_LEDS)
    ws2812_spi_led_strip_init(SPI2_HOST, CONFIG_LED_STRIP_MAX_LEDS);
    s_led_strip = ws2812_spi_led_new_buf(CONFIG_LED_STRIP_MAX_LEDS);
    sh_register_cmd(&_register_cmd);
#endif
}

void ws2812_spi_shell_unregister(void)
{
    sh_unregister_cmd(&_register_cmd);
}

static int _set_value(const char *argv[]) { return SET_VAR(&s_value, 0, 0x100); }

SH_CMD_FN(set)
{
    uint32_t pin = 0, index = 0, red = 0, green = 0, blue = 0;
    if (argc < 2)
    {
        sh_echo(sh_hdl, "输入少于 2 个参数\r\n");
        return -1;
    }

    if (argc >= 1 && _set_value(&argv[0]))
        return -1;
    pin = *(volatile __typeof(s_value) *)&s_value;

    if (argc >= 2 && _set_value(&argv[1]))
        return -1;
    index = *(volatile __typeof(s_value) *)&s_value;

    if (argc >= 3 && _set_value(&argv[2]))
        return -1;
    red = *(volatile __typeof(s_value) *)&s_value;

    if (argc >= 4 && _set_value(&argv[3]))
        return -1;
    green = *(volatile __typeof(s_value) *)&s_value;

    if (argc >= 5 && _set_value(&argv[4]))
        return -1;
    blue = *(volatile __typeof(s_value) *)&s_value;

    ws2812_spi_led_strip_set_pixel(s_led_strip, index, red, green, blue);
#if (CONFIG_LED_STRIP_MAX_LEDS)
    ws2812_spi_led_strip_refresh(s_led_strip, CONFIG_LED_STRIP_MAX_LEDS, pin);
#else
    ws2812_spi_led_strip_refresh(s_led_strip, 126, pin);
#endif
    return 0;
}

SH_CMD_FN(clr)
{
    uint32_t pin = 0;
    if (argc < 1)
    {
        sh_echo(sh_hdl, "输入少于 1 个参数\r\n");
        return -1;
    }

    _set_value(&argv[0]);
    pin = *(volatile __typeof(s_value) *)&s_value;

    ws2812_spi_led_strip_clear(s_led_strip);
#if (CONFIG_LED_STRIP_MAX_LEDS)
    ws2812_spi_led_strip_refresh(s_led_strip, CONFIG_LED_STRIP_MAX_LEDS, pin);
#else
    ws2812_spi_led_strip_refresh(s_led_strip, 126, pin);
#endif
    return 0;
}
