/****************************************************************************
 ** ScStw Libraries
 ** Copyright (C) 2020  Itsblue development
 **
 ** This program is free software: you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
 ** the Free Software Foundation, either version 3 of the License, or
 ** (at your option) any later version.
 **
 ** This program is distributed in the hope that it will be useful,
 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ** GNU General Public License for more details.
 **
 ** You should have received a copy of the GNU General Public License
 ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/

#include "scstwsetting.h"
#include "scstwsettings.h"
#include <QtDebug>

ScStwSetting::ScStwSetting(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent) : QObject(parent)
{
    this->scStwSettings = scStwSettings;
    connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSetting::handleSettingChange);
    this->key = key;
    this->keyLevel = keyLevel;
    this->handleSettingChange(-1, this->keyLevel, QVariant());
}

QVariant ScStwSetting::getValue() {
    qDebug() << "Getting setting: " << this->key << " has to reload: " << this->hasToReload;
    if(this->hasToReload) {
        this->valueCache = this->scStwSettings->readSetting(this->key, this->keyLevel);
        this->hasToReload = false;
    }

    return this->valueCache;
}

void ScStwSetting::setValue(QVariant value) {
    if(value != this->valueCache) {
        this->scStwSettings->writeSetting(this->key, this->keyLevel, value);
    }
}

void ScStwSetting::handleSettingChange(int key, int keyLevel, QVariant value) {
    if(keyLevel == this->keyLevel && key == this->key) {
        this->valueCache = value;
        qDebug() << "value changed!!! key: " << key << " new value " << value;
        emit this->valueChanged();
    }
    else if(key == -1 && this->key != -1 && this->keyLevel != -1 && this->keyLevel == keyLevel) {
        qDebug() << "value changed!!! key: " << key << " new value " << value;
        this->hasToReload = true;
        emit this->valueChanged();
    }
}
