//
// Created by Mr.V on 2024/2/19.
//

#include "iniUtil.h"
#include <QSettings>
#include <QFile>
#include <QTextCodec>

int IniUtils::writeConfig( QString file, QString group, QString key, QString val)
{
    if(file.isEmpty() || file.isNull())
    {
        return -1;
    }
    QSettings* mset = new QSettings(file, QSettings::IniFormat);
    mset->setIniCodec(QTextCodec::codecForName("UTF-8"));
    mset->beginGroup(group);
    mset->setValue(key, val);
    mset->endGroup();
    return 0;
}

QString IniUtils::readConfig(QString file, QString group, QString key)
{
    if(file.isEmpty() || file.isNull())
    {
        return "";
    }
    QSettings* mset = new QSettings(file, QSettings::IniFormat);
    mset->setIniCodec(QTextCodec::codecForName("UTF-8"));
    QString mdir = "";
    mset->beginGroup(group);
    mdir = mset->value(key, "").toString();
    mset->endGroup();
    return mdir;
}
/**
 * @brief writeArrayConfig 写数组数据
 * @param file
 * @param group
 * @param key
 * @param val
 * @return
 */
int IniUtils::writeArrayConfig(QString file, QString group, QString key, QList<QString> val)
{
    if(file.isEmpty() || file.isNull())
    {
        return -1;
    }

    QSettings* mset = new QSettings(file, QSettings::IniFormat);
    mset->setIniCodec("UTF-8");
    mset->beginGroup(group);
    mset->beginWriteArray("array");

    for(int i = 0; i < val.size(); i++)
    {
        mset->setArrayIndex(i);
        mset->setValue(key, val.at(i));
    }
    mset->endArray();
    mset->endGroup();
    return 0;
}

/**
 * @brief readArrayConfig 读数组数据
 * @param file
 * @param group
 * @param key
 * @return
 */
QList<QString> IniUtils::readArrayConfig(QString file, QString group, QString key)
{
    QList<QString> mdir;
    mdir.clear();
    if(file.isEmpty() || file.isNull())
    {
        return mdir;
    }
    QSettings* mset = new QSettings(file, QSettings::IniFormat);
    mset->setIniCodec("UTF-8");
    mset->beginGroup(group);

    int size = 0;

    size = mset->beginReadArray("array");
    for(int i = 0; i < size; i ++)
    {
        mset->setArrayIndex(i);
        mdir.append(mset->value(key, "").toString());
    }
    mset->endArray();
    mset->endGroup();
    return mdir;
}