/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * Copyright: 2019 Tianjin KYLIN Information Technology Co., Ltd. *
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */


#include <signal.h>

#include "ukuipanelapplication.h"
#include "ukuipanelapplication_p.h"
#include "ukuipanel.h"
//#include <UKUi/Settings>
#include "common/ukuisettings.h"
#include <QtDebug>
#include <QUuid>
#include <QScreen>
#include <QWindow>
#include <KWindowEffects>
#include <QCommandLineParser>
#include <QFile>

#define CONFIG_FILE_BACKUP     "/usr/share/ukui/panel.conf"
#define CONFIG_FILE_LOCAL      ".config/ukui/panel.conf"

UKUIPanelApplicationPrivate::UKUIPanelApplicationPrivate(UKUIPanelApplication *q)
    : mSettings(0),
      q_ptr(q)
{
}


UKUIPanelApplication::UKUIPanelApplication(int& argc, char** argv)
    : QApplication(argc, argv, true),
    d_ptr(new UKUIPanelApplicationPrivate(this))

{
    translator();
    // bind to SIGTERM siganl to exit with code 15
    signal(SIGTERM, sigtermHandler);

    Q_D(UKUIPanelApplication);

    QCoreApplication::setApplicationName(QLatin1String("ukui-panel"));
    const QString VERINFO = QStringLiteral(UKUI_PANEL_VERSION
                                           "\nlibukui   " ""
                                           "\nQt        " QT_VERSION_STR);

    QCoreApplication::setApplicationVersion(VERINFO);

    QCommandLineParser parser;
    parser.setApplicationDescription(QLatin1String("UKUi Panel"));
    parser.addHelpOption();
    parser.addVersionOption();

    //添加其他参数
    QCommandLineOption configFileOption(QStringList()
            << QLatin1String("c") << QLatin1String("config") << QLatin1String("configfile"),
            QCoreApplication::translate("main", "Use alternate configuration file."),
            QCoreApplication::translate("main", "Configuration file"));
    parser.addOption(configFileOption);

    QCommandLineOption panelResetOption(QStringList()
            << QLatin1String("r") << QLatin1String("reset") << QLatin1String("panel reset"),
            QCoreApplication::translate("main", "ukui-panel set mode "),
            QCoreApplication::translate("main", "panel set option"));
    parser.addOption(panelResetOption);

    parser.process(*this);

    const QString configFile = parser.value(configFileOption);
    if (configFile.isEmpty())
    {
        QString defaultConf = QString(PLUGIN_DESKTOPS_DIR)+"/../";
        QString loaclCong = QString(qgetenv("HOME"))+"/.config/ukui/";
        QFile file(loaclCong+"panel.conf");
        if(!file.exists()){
            copyFileToPath(defaultConf,loaclCong,"panel.conf",false);
//            QFile::copy(CONFIG_FILE_BACKUP,QString(qgetenv("HOME"))+CONFIG_FILE_LOCAL);
        }
        d->mSettings = new UKUi::Settings(QLatin1String("panel"), this);
        if(!d->mSettings->contains("plugins")){
            QFile::remove(QString(qgetenv("HOME"))+CONFIG_FILE_LOCAL);
            QFile::copy(CONFIG_FILE_BACKUP,QString(qgetenv("HOME"))+CONFIG_FILE_LOCAL);
            d->mSettings = new UKUi::Settings(QLatin1String("panel"), this);
        }
    }
    else
    {
        qDebug()<<"configFile.is not Empty"<<endl;
        d->mSettings = new UKUi::Settings(configFile, QSettings::IniFormat, this);
    }

    const QString panelReset = parser.value(panelResetOption);
    if(panelReset.isEmpty()){qDebug()<<"ukui-panel --reset";}
    if(panelReset == "reset"){system("rm $HOME/.config/ukui/panel.conf");}
    if(panelReset == "replace"){qDebug()<<"ukui-panel --replace";}
    if(panelReset == "calendar-new"){system("/usr/share/ukui/ukui-panel/ukui-panel-config.sh calendar new && killall ukui-panel");}
    if(panelReset == "calendar-old"){system("/usr/share/ukui/ukui-panel/ukui-panel-config.sh calendar old && killall ukui-panel");}
    connect(this, &QCoreApplication::aboutToQuit, this, &UKUIPanelApplication::cleanup);


    QStringList panels = d->mSettings->value("panels").toStringList();

    // WARNING: Giving a separate icon theme to the panel is wrong and has side effects.
    // However, it is optional and can be used as the last resort for avoiding a low
    // contrast in the case of symbolic SVG icons. (The correct way of doing that is
    // using a Qt widget style that can assign a separate theme/QPalette to the panel.)
    m_globalIconTheme = QIcon::themeName();
    const QString iconTheme = d->mSettings->value("iconTheme").toString();
    if (!iconTheme.isEmpty())
        QIcon::setThemeName(iconTheme);

    if (panels.isEmpty())
    {
        panels << "panel1";
    }

#if (QT_VERSION < QT_VERSION_CHECK(5,7,0))
    for(int it=0;it<panels.size();it++){
        const QString &i=panels[it];
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
    for(const QString& i : qAsConst(panels)){
#endif

        addPanel(i);
    }
}

UKUIPanelApplication::~UKUIPanelApplication()
{
    delete d_ptr;
}

void UKUIPanelApplication::cleanup()
{
    qDeleteAll(m_panels);
}


UKUIPanel* UKUIPanelApplication::addPanel(const QString& name)
{
    Q_D(UKUIPanelApplication);

    UKUIPanel *panel = new UKUIPanel(name, d->mSettings);
    KWindowEffects::enableBlurBehind(panel->winId(),true);
    m_panels << panel;

    // reemit signals
    connect(panel, &UKUIPanel::pluginAdded, this, &UKUIPanelApplication::pluginAdded);
    connect(panel, &UKUIPanel::pluginRemoved, this, &UKUIPanelApplication::pluginRemoved);

    return panel;
}

bool UKUIPanelApplication::isPluginSingletonAndRunnig(QString const & pluginId) const
{
    for (auto const & panel : m_panels)
        if (panel->isPluginSingletonAndRunnig(pluginId))
            return true;

    return false;
}

void UKUIPanelApplication::sigtermHandler(int signo)
{
    qDebug() << "Caught SIGTERM signal, exit with SIGTERM";
    exit(signo);
}

void UKUIPanelApplication::translator()
{
    QTranslator *translator = new QTranslator(this);
    translator->load(QLocale(), "panel", "_", PANEL_TRANSLATION_DIR);
    QCoreApplication::installTranslator(translator);
}

bool UKUIPanelApplication::copyFileToPath(QString sourceDir ,QString toDir, QString fileName, bool coverFileIfExist)
{
    if (sourceDir == toDir){
        return true;
    }
    if (!QFile::exists(sourceDir+fileName)){
        return false;
    }
    QDir *createDir = new QDir;
    bool dirExist = createDir->exists(toDir);
    if(!dirExist)
        createDir->mkdir(toDir);
    QFile *createFile = new QFile;
    bool fileExist = createFile->exists(toDir+fileName);
    if (fileExist){
        if(coverFileIfExist){
            createFile->remove(toDir+fileName);
        }
    }//end if
    free(createDir);
    free(createFile);

    if(!QFile::copy(sourceDir+fileName, toDir+fileName))
    {
        return false;
    }
    return true;
}
