#include <iostream>
#include <fstream>
#include "toml.hpp"
#include <chrono>
#include <thread>
#include "SerialPort.h"
#include "LedCommand.h"

using namespace toml;

// 常红灯
void alwaysRed(SerialPort &serial)
{
    LedCommand cmd;
    cmd.setColor(255, 0, 0); // 红色
    cmd.setExtCount(1);
    auto packet = cmd.serialize();

    std::cout << "发送常红数据包：";
    for (auto b : packet)
        printf(" %02X", b);
    std::cout << std::endl;

    if (!serial.writeData(packet.data(), packet.size()))
        std::cerr << "发送数据失败" << std::endl;
}

// 黄色呼吸灯效果
void yellowBreathing(SerialPort &serial)
{
    LedCommand cmd;
    std::cout << "开始黄色呼吸灯效果..." << std::endl;

    // 呼吸灯亮度从0升到255
    for (int i = 0; i <= 255; i += 15)
    {
        cmd.setColor(i, i, 0);
        cmd.setExtCount(1);
        auto packet = cmd.serialize();
        if (!serial.writeData(packet.data(), packet.size()))
            std::cerr << "发送数据失败" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    // 呼吸灯亮度从255降到0
    for (int i = 255; i >= 0; i -= 15)
    {
        cmd.setColor(i, i, 0);
        cmd.setExtCount(1);
        auto packet = cmd.serialize();
        if (!serial.writeData(packet.data(), packet.size()))
            std::cerr << "发送数据失败" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main()
{
    std::string port = "/dev/ttyS0";
    int baudrate = 115200;

    std::ifstream ifs("config.toml");
    if (ifs)
    {
        try
        {
            auto data = toml::parse(ifs);
            if (auto serial = toml::find(data, "serial"); !serial.is_table())
            {
                std::cerr << "serial 部分不存在或格式错误" << std::endl;
                return 1;
            }
            port = toml::find<std::string>(data, "serial", "port");
            baudrate = toml::find<int>(data, "serial", "baudrate");
        }
        catch (const std::exception &e)
        {
            std::cerr << "解析 config.toml 失败: " << e.what() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cerr << "无法打开 config.toml 文件，使用默认参数。" << std::endl;
    }

    std::cout << "串口号: " << port << "\n波特率: " << baudrate << std::endl;

    SerialPort serial;
    if (!serial.openPort(port, baudrate))
    {
        return 1;
    }

    // 调用函数实现两个动作
    alwaysRed(serial);
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 保持常红2秒
    yellowBreathing(serial);

    serial.closePort();

    return 0;
}
