//
// Created by Mr.V on 2024/1/26.
//

#include <QSettings>
#include "ConfigUtil.h"
#include "iniUtil.h"

ConfigUtil::ConfigUtil() = default;

ConfigUtil::~ConfigUtil() = default;

bool ConfigUtil::readBaseConfig(const QString &configFile, QString &errorMessage, ai_matrix::BaseConfig &config) {
    try {
        if (configFile.isEmpty() || configFile.isNull()) {
            errorMessage = "配置文件地址为空，读取配置文件失败！";
            return false;
        }
        QSettings* mset = new QSettings(configFile, QSettings::IniFormat);
        mset->setIniCodec(QTextCodec::codecForName("UTF-8"));
        QString mdir = "";
        mset->beginGroup("base");
        config.comName = mset->value("com_name", "").toString();
        config.baud = mset->value("baud", 19200).toInt();
        config.trackName = mset->value("track_name", 1).toInt();
        config.magnetSteelOrder = mset->value("magnet_steel_order", "").toString();
        config.upResult = mset->value("up_result", false).toBool();

        mset->endGroup();
    } catch (const std::exception &e) {
        errorMessage = e.what();
        return false;
    }
    return true;
}

bool ConfigUtil::readInterfaceConfig(const QString &configFile, QString &errorMessage,
                                     ai_matrix::InterfaceConfig &config) {
    try {
        if (configFile.isEmpty() || configFile.isNull()) {
            errorMessage = "配置文件地址为空，读取配置文件失败！";
            return false;
        }
        QSettings* mset = new QSettings(configFile, QSettings::IniFormat);
        mset->setIniCodec(QTextCodec::codecForName("UTF-8"));
        mset->beginGroup("interface");
        config.httpIp = mset->value("http_ip", "").toString();
        config.httpPort = mset->value("http_port", "").toInt();
        config.tokenPath = mset->value("token_path", 19200).toString();
        config.upResultPath = mset->value("up_result_path", 1).toString();
        config.username = mset->value("username", "").toString();
        config.password = mset->value("password", false).toString();

        mset->endGroup();
    } catch (const std::exception &e) {
        errorMessage = e.what();
        return false;
    }
    return true;
}