#include "general_spkbox.h"

#include <httplib.h>

#include "common/spdlog/logging.h"

namespace zsy
{
    GeneralSpkbox::GeneralSpkbox(const SpkboxConfig &config)
        : Spkbox(config), playEndpoint("/v1/speech")
    {
    }

    void GeneralSpkbox::play(const std::string &content, uint8_t times)
    {
        try
        {
            if (times < 1)
            {
                times = 1;
            }
            LOGGER_INFO("正在播放语音，设备名称：{}", config.name());

            LOGGER_INFO("播放内容：{}", content);
            httplib::Headers headers = {
                {"Content-Type", "application/json"}
            };

            auto body = JSON::toJsonStr(PlayParam{
                .loop = {
                    .times = times
                },
                .text = content
            });
            LOGGER_INFO("播放语音：{}{} {}", config.server(), playEndpoint, body);

            httplib::Client cli(config.server());
            cli.set_connection_timeout(20);
            cli.set_read_timeout(30);
            cli.set_write_timeout(20);

            if (auto response = cli.Post(playEndpoint.c_str(), headers, body, "application/json"))
            {
                LOGGER_INFO("语音播放结果：{}", response->body);
                if (const int status = response->status; status >= 300 || status < 200)
                {
                    LOGGER_ERROR("语音播放失败，HTTP状态码：{}", status);
                } else
                {
                    const auto json = nlohmann::json::parse(response->body);
                    if (auto [code, message] = json.get<PlayResult>(); code == 200)
                    {
                        LOGGER_INFO("语音播放成功");
                    } else
                    {
                        LOGGER_ERROR("语音播放失败，错误：{}", message);
                    }
                }
            } else
            {
                LOGGER_ERROR("语音播放失败，错误：{}", httplib::to_string(response.error()));
            }
        } catch (const std::exception &e)
        {
            LOGGER_ERROR("语音播放失败，错误：{}", e.what());
        } catch (...)
        {
            LOGGER_ERROR("未知异常，语音播放失败");
        }
    }
} // zsy
