/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * 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 <https://www.gnu.org/licenses/>.
 *
 * Authors: wangyan <wangyan@kylinos.cn>
 *
 */

#include "touchscreen.h"
#include "pluginentry.h"

#include <QDebug>
#include <QTranslator>
#include <QGSettings>
#include <QApplication>

TouchScreen::TouchScreen()
            :m_entry(nullptr)
{
    QTranslator *translator = new QTranslator(this);
    translator->load("/usr/share/TouchCalibrate/translations/" + QLocale::system().name());
    QApplication::installTranslator(translator);


}

TouchScreen::~TouchScreen()
{
}

QWidget *TouchScreen::pluginUi()
{
    if (nullptr == m_entry) {
        m_entry = new PluginEntry(this);
        connect(m_entry, &PluginEntry::widgetEnableChanged, this, &TouchScreen::onEnableChanged);
    }
    return m_entry->widget();
}

QString TouchScreen::plugini18nName() {
    return tr("TouchCalibrate");
}

int TouchScreen::pluginTypes() {
    return FunType::SYSTEM;
}

const QString TouchScreen::name() const {

    return QStringLiteral("TouchCalibrate");
}

QIcon TouchScreen::icon() const
{
    return QIcon::fromTheme("ukui-calibrate-symbolic");
}

bool TouchScreen::isShowOnHomePage() const
{
    return false;
}

bool TouchScreen::isEnable() const
{
    return PluginEntry::widgetEnable();
}

QString TouchScreen::translationPath() const
{
    return "/usr/share/TouchCalibrate/translations/%1.ts";
}

void TouchScreen::initSearchText()
{
    //~ contents_path /TouchCalibrate/monitor
    tr("monitor");

    //~ contents_path /TouchCalibrate/touch id
    tr("touch id");

    //~ contents_path /TouchCalibrate/input device
    tr("input device");

    //~ contents_path /TouchCalibrate/map
    tr("map");
}

void TouchScreen::onEnableChanged(bool enabled)
{
    const QByteArray schema("org.ukui.control-center.plugins");
    if(!QGSettings::isSchemaInstalled(schema)) {
        qWarning() << "GSetting "<< schema << "don't be installed";
        return;
    }
    QString path("/org/ukui/control-center/plugins/TouchCalibrate/");
    QGSettings settings(schema, path.toUtf8());

    QVariant currentEnabled = settings.get("show");
    if (!currentEnabled.isValid() || currentEnabled.isNull()) {
        qWarning() << "QGSettins get plugin show property error";
        return;
    }

    if (currentEnabled != enabled)
        settings.set("show", enabled);
}
