/*
 * Copyright (C) 2019 Tianjin KYLIN Information Technology 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, 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/&gt;.
 *
 */

#include "languageframe.h"
#include <QWidget>
#include <QGridLayout>
#include <QVBoxLayout>
#include <QDebug>
#include <QProcess>
#include <QApplication>
#include <QLocale>
#include <QKeyEvent>

#include <QFile>
#include <QTextStream>
#include "../PluginService/klinguist.h"
#include "../PluginService/ksystemenv.h"
#include "../PluginService/kdir.h"
#include "../PluginService/ui_unit/keyeventcontrol.h"
#include "../PluginService/ui_unit/xrandrobject.h"
#include <QDir>
#include <QFileInfo>
using namespace KServer;

namespace KInstaller {

LanguageFrame::LanguageFrame(QWidget *parent) : MiddleFrameManager(parent)
{
 #ifdef   LANGUAGE_ZH_CN
    QPair<QString,QPair<PushButtonCheck*,QString>> pir1;
    pir1.first="zh_CN";
    pir1.second.first=NULL;
    pir1.second.second="中文(简体)";
    emulang.append(pir1);
  #endif

 #ifdef LANGUAGE_ZH_HK
   QPair<QString,QPair<PushButtonCheck*,QString>> pir5;
   pir5.first="zh_HK";
   pir5.second.first=NULL;
   pir5.second.second="中文(繁體)";
   emulang.append(pir5);
 #endif

 #ifdef LANGUAGE_EN_US
    QPair<QString,QPair<PushButtonCheck*,QString>> pir2;
    pir2.first="en_US";
    pir2.second.first=NULL;
    pir2.second.second="English";
    emulang.append(pir2);
   #endif

 #ifdef LANGUAGE_BO_CN
    QPair<QString,QPair<PushButtonCheck*,QString>> pir3;
    pir3.first="bo_CN";
    pir3.second.first=NULL;
    pir3.second.second="བོད་ཡིག";//藏语
    emulang.append(pir3);
   #endif

 #ifdef LANGUAGE_RU_RU
    QPair<QString,QPair<PushButtonCheck*,QString>> pir4;
    pir4.first="ru_RU";
    pir4.second.first=NULL;
    pir4.second.second="русский язык";//俄语
    emulang.append(pir4);
  #endif

 #ifdef LANGUAGE_UG_CN
   QPair<QString,QPair<PushButtonCheck*,QString>> pir6;
   pir6.first="ug_CN";
   pir6.second.first=NULL;
   pir6.second.second="Uyghur";//维吾尔语
   emulang.append(pir6);
 #endif

#ifdef LANGUAGE_KK_CN
  QPair<QString,QPair<PushButtonCheck*,QString>> pir7;
  pir7.first="kk_CN";
  pir7.second.first=NULL;
  pir7.second.second="Қазақ";//哈萨克语
  emulang.append(pir7);
#endif

#ifdef LANGUAGE_KY_CN
  QPair<QString,QPair<PushButtonCheck*,QString>> pir8;
  pir8.first="ky_CN";
  pir8.second.first=NULL;
  pir8.second.second="قىرعىز تىلى";//柯尔克孜语
  emulang.append(pir8);
#endif

    //翻译列表，按照从上倒下的按键顺序排列
  //  emulang.append(qMakePair("zh_CN","中文(简体)"));
//    emulang.append(qMakePair("en_US","English"));
//    emulang.append(qMakePair("bo_CN","བོད་ཡིག"));
//    emulang.append(qMakePair("ru_RU","русский язык"));

    QList<LanguageSetInINI> LanguageList = ReadLanguageIni();//获取安装器已支持语言的列表
    for (int i = 0; i < LanguageList.size(); ++i)
    {
        if(LanguageList.at(i).lsInCurrentList)//加载显示语言列表
        {
            QPair<QString,QPair<PushButtonCheck*,QString>> pir;
            pir.first=LanguageList.at(i).Language;
            pir.second.first=NULL;
            pir.second.second=LanguageList.at(i).display;
            emulang.append(pir);
        }
    }

    m_pQtTranslator = new QTranslator;
    m_pCurTranslator = new QTranslator;
    this->initNextBnt();
    initUI();
    addStyleSheet();
//    readSettingIni();
    this->setFocus();
}

LanguageFrame::~LanguageFrame()
{
    for(int k=0;k< emulang.count();k++)
    {
        PushButtonCheck * m_Btn = emulang[k].second.first;
        if(m_Btn)
            delete m_Btn;
    }
}

void LanguageFrame::initUI()
{
    QGridLayout* gLayoutl = new QGridLayout();
    gLayoutl->setContentsMargins(0, 0, 0, 0);
    // widget->setGeometry(0, 0, this->width(), this->height());
    m_Widget->setLayout(gLayoutl);
    gLayoutl->setColumnStretch(0, 3);
    gLayoutl->setColumnStretch(1, 2);
    gLayoutl->setColumnStretch(2, 3);

    int lay_index=0;
    gLayoutl->addItem(new QSpacerItem(10, 40, QSizePolicy::Expanding, QSizePolicy::Preferred), lay_index, 1, 1, 1);
    lay_index++;
    m_mainTitle = new QLabel();
    m_mainTitle->setObjectName("mainTitle");
    gLayoutl->addWidget(m_mainTitle, lay_index, 1, 1, 1, Qt::AlignCenter);
    lay_index++;
    gLayoutl->addItem(new QSpacerItem(10, 40, QSizePolicy::Expanding, QSizePolicy::Preferred), lay_index, 1, 1, 1);
    lay_index++;

    for(int k=0;k< emulang.count();k++)
    {
        PushButtonCheck *m_Btn = new PushButtonCheck(emulang.at(k).second.second);
        m_Btn->setObjectName(emulang.at(k).first);
        connect(m_Btn,&PushButtonCheck::clicked_obj,this,&LanguageFrame::changeLanguage);
        connect(this,&LanguageFrame::changeLanguage_sig,m_Btn,&PushButtonCheck::other_clicked_slot);
        emulang[k].second.first = m_Btn;
// why should so ???
// get system locale to show
//        if(k==0)
//        {         
//            m_curSystenlocal=emulang.at(k).first;
//            changeLanguage(m_Btn);
//            writeSettingIni();
//        }
       m_curSystenlocal=QLocale::system().name();
       if (m_curSystenlocal == emulang.at(k).first || (m_curSystenlocal == "C" && emulang.at(k).first == "en_US") )
       {
               changeLanguage(m_Btn);//默认语言为当前系统语言
       }
       else if(0 == k)
       {
               changeLanguage(m_Btn);//如果ky-langcurrent.cfg中的当前显示语言列表中不含当前系统语言时，则默认语言为此列表中第一个语言
       }
        gLayoutl->addWidget(m_Btn, lay_index, 1, 1, 1, Qt::AlignCenter);
        lay_index++;
        gLayoutl->addItem(new QSpacerItem(8, 24, QSizePolicy::Expanding, QSizePolicy::Minimum), lay_index, 1, 1, 1);
        lay_index++;
    }

    gLayoutl->addItem(new QSpacerItem(10, 200, QSizePolicy::Expanding, QSizePolicy::Expanding), lay_index, 1, 1, 1);
    translateStr();

}

void LanguageFrame::addStyleSheet()
{
    QFile file(":/res/qss/KChoiceLanguage.css");
    file.open(QFile::ReadOnly);
    QTextStream filetext(&file);
    QString stylesheet = QString("");
    stylesheet = filetext.readAll();
    file.close();

    this->setStyleSheet(stylesheet);
}

//读写systemsetting.ini文件
void LanguageFrame::readSettingIni()
{
//    m_curSystenlocal = ReadSettingIni("config", "language");
//    should not read config
//    get locale from system
      m_curSystenlocal = QLocale::system().name();
}

void LanguageFrame::writeSettingIni()
{
    QString strLang = ReadSettingIni("config", "language");
    if(strLang != m_curSystenlocal)
        WriteSettingToIni("config", "language", m_curSystenlocal);
}

void LanguageFrame::changeLanguage(PushButtonCheck* obj)
{
    QString langPath = GetKylinInstallPath() + "language/";
    emit changeLanguage_sig(obj->objectName());

    if (m_curSystenlocal != obj->objectName()) {
        qApp->removeTranslator(m_pCurTranslator);
        qApp->removeTranslator(m_pQtTranslator);
    }

    m_curSystenlocal = obj->objectName();
    if (m_pCurTranslator->load(langPath + m_curSystenlocal + ".qm")) {
        qApp->installTranslator(m_pCurTranslator);
    }

    if (m_pQtTranslator->load(langPath + "qt_"+m_curSystenlocal+".qm")) {
        qApp->installTranslator(m_pQtTranslator);
    }

    qDebug()<<"language qm file path="<<langPath;
    qDebug()<<"current language="<<m_curSystenlocal;
    unsetenv("LANG");
    setenv("LANG", obj->objectName().toStdString().c_str(),1);
    writeSettingIni();
    this->setFocus();
    obj->setChecked(true);
    qApp->setProperty("Language", m_curSystenlocal);
}

void LanguageFrame::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::LanguageChange) {
        translateStr();
    } else {
        QWidget::changeEvent(event);
    }
}

void LanguageFrame::translateStr()
{
    m_mainTitle->setText(tr("Select Language"));
    m_nextBtn->setText(tr("Next"));
}

void LanguageFrame::clickNextButton()
{
    writeSettingIni();
    emit signalStackPageChanged(1);
}

void LanguageFrame::keyPressEvent(QKeyEvent *event)
{
    this->setFocus();
    qDebug() << event->key() << "key pressed!";
    qDebug() << Q_FUNC_INFO << "keyPressEvent";
    if (event->key() == Qt::Key_Up) {//向上键
        int k = 0;
        for (k = 0; k < emulang.count(); k++) {
            if (m_curSystenlocal.compare(emulang.at(k).first)==0)
                break;
        }
        if (k == 0) {
            k = emulang.count()-1;
        } else {
            k = k - 1;
        }
        m_curSystenlocal = emulang.at(k).first;
        changeLanguage(emulang.at(k).second.first);//bug131879安装时使用键盘按钮切换English，到下一步许可协议展示的是中文（即鼠标可用但是键盘的选择无效）
    } else if (event->key() == Qt::Key_Down) {//向下键
        int k = 0;
        for (k = 0; k < emulang.count(); k++) {
            if (m_curSystenlocal.compare(emulang.at(k).first) == 0)
                break;
        }

        if ((++k) >= emulang.count())
            k=0;
        m_curSystenlocal = emulang.at(k).first;
        changeLanguage(emulang.at(k).second.first);//bug131879
    } else if (event->key() == Qt::Key_Enter) {//小键盘中回车键
        emit enterpressed();
    } else if (event->key() == Qt::Key_Return) {//大键盘中回车键
        emit enterpressed();
    } else if (event->key() == Qt::Key_Backspace) {
        emit backspacepressed();
    } else
        QWidget::keyPressEvent(event);
}

}
