#include "Settings.h"
#include "Core/Logger.h"
#include <boost/algorithm/string/trim.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <filesystem>
#include <thread>

constexpr auto SettingsFilePath = "settings.xml";

namespace Older {
Settings::Settings() {
    if (!std::filesystem::exists(SettingsFilePath)) {
        save();
    }
    load();
}

void Settings::save() {
    using namespace boost::property_tree;
    ptree ptree;
    ptree.put("Application.Threads", std::thread::hardware_concurrency());
    ptree.put("Application.SqlitePath", m_sqlitePath);

    ptree.put("Application.HttpServer.Address", m_server);
    ptree.put("Application.HttpServer.DocumentRoot", m_documentRoot);
    ptree.put("Application.HttpServer.DocumentRoot.<xmlcomment>", "静态网页文件存放位置,为空时网站统计将不判断页面页面是否存在");

    xml_writer_settings<std::string> settings('\t', 1);
    write_xml(SettingsFilePath, ptree, std::locale(), settings);
}

void Settings::load() {
    using namespace boost::property_tree;
    ptree ptree;
    try {
        read_xml(SettingsFilePath, ptree);
        m_sqlitePath = ptree.get<std::string>("Application.SqlitePath");
        m_threads = ptree.get<uint32_t>("Application.Threads");

        m_server = ptree.get<std::string>("Application.HttpServer.Address");
        m_documentRoot = ptree.get<std::string>("Application.HttpServer.DocumentRoot");
        boost::algorithm::trim(m_documentRoot);
    } catch (const xml_parser_error &error) {
        LOG(error) << "parse " << SettingsFilePath << " failed: " << error.message();
    }
}

uint32_t Settings::threads() const {
    return m_threads;
}

std::string Settings::server() const {
    return m_server;
}

uint16_t Settings::port() const {
    return m_port;
}

std::string Settings::documentRoot() const {
    return m_documentRoot;
}

std::string Settings::live2dModelsRoot() const {
    return m_live2dModelsRoot;
}

std::string Settings::sqlitePath() const {
    return m_sqlitePath;
}

} // namespace Older