/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * Copyright (C) 2019 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 2 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */
#include "addlanguagedialog.h"
#include "ui_addlanguagedialog.h"
#include <QTranslator>
#include <QToolTip>
#include <QCompleter>
#include <kysdk/applications/accessinfohelper.h>

using namespace kdk;

AddLanguageDialog::AddLanguageDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddLanguageDialog),
    mSearchLineEdit(new KSearchLineEdit(this))
{
    ui->setupUi(this);
    this->setWindowTitle(tr("Add Language"));
    initDict();
    QCompleter* completer = new QCompleter(this);
    mSearchLineEdit->setCompleter(completer);
    mSearchLineEdit->completer()->popup()->setVisible(false);
    mSearchLineEdit->setClearButtonEnabled(true);
    ui->frame->layout()->addWidget(mSearchLineEdit);
    ui->tableView->setFrameShape(QFrame::Panel);
    mode = new QStandardItemModel(this);
    m_proxyModel = new QSortFilterProxyModel(this);
    m_proxyModel->setSourceModel(mode);
    m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    ui->tableView->setModel(m_proxyModel);
    ui->tableView->setAlternatingRowColors(true);
    ui->tableView->setMouseTracking(true);
    ui->tableView->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
    connect(ui->tableView, &QTableView::entered,
            this, [=](const QModelIndex &index){
        QString mStr = index.data().toString();
        QFontMetrics fontMetrics(this->font());
        int fontSize = fontMetrics.width(mStr);
        if (fontSize - 16 > 416) {
            QToolTip::showText(QCursor::pos(), mStr);
        }
    });
    ui->tableView->verticalHeader()->setVisible(false);//隐藏垂直表头
    ui->tableView->horizontalHeader()->setVisible(false);//隐藏水平表头
    ui->tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->tableView->setShowGrid(false);//不显示表格线
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//水平表格自动拉伸
    ui->tableView->verticalHeader()->setDefaultSectionSize(36);//行高默认为36
    this->setWindowModality(Qt::ApplicationModal); //模态

    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    mode->setColumnCount(1);
    ui->yesBtn->setEnabled(false);
    ui->yesBtn->setProperty("isImportant", true);
    ui->yesBtn->setDefault(true);

    KDK_EXTEND_ALL_INFO_FORMAT(mSearchLineEdit, "Area", "", "");
    KDK_EXTEND_ALL_INFO_FORMAT(ui->tableView, "Area", "", "");
    KDK_EXTEND_ALL_INFO_FORMAT(ui->noBtn, "Area", "", "");
    KDK_EXTEND_ALL_INFO_FORMAT(ui->yesBtn, "Area", "", "");

    /*暂时使用自定义的语言，不使用apt获取的
    languageInfo = new LanguageInfo;
    connect(languageInfo,
            &LanguageInfo::initFinished,
            this,
            [=](QMap<QString, QString> availableLangMap,QMap<QString, QString> installedLangMap){
            this->availableLangMap = availableLangMap;
            this->installedLangMap = installedLangMap;
            mode->setRowCount(availableLangMap.count());

            QMap<QString, QString>::const_iterator it = availableLangMap.constBegin();
            for (int i = 0; i < mode->rowCount(); i++, it++) {
                mode->setItem(i, new QStandardItem(it.value()));
            }
            initCompleter();
    });
    languageInfo->init();
    */
    initCompleter();
    connect(ui->yesBtn,&QPushButton::clicked,this,[=]() {
        QModelIndexList indexList =  ui->tableView->selectionModel()->selectedRows();
        QStringList selectedLanguageList = {};
        for (QModelIndex a:indexList) {
            selectedLanguageList.append(ui->tableView->model()->data(a).toString());
        }
        qDebug() << Q_FUNC_INFO << "select LanguageList" << selectedLanguageList;
        Q_EMIT addShowLanguage(selectedLanguageList);
        this->hide();
    });

    connect(ui->noBtn,&QPushButton::clicked,this,[=]() {
        this->hide();
    });

    connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this,
            &AddLanguageDialog::onSelectionChanged);
}

void AddLanguageDialog::setConfirmEnable(bool enabled) {
    ui->yesBtn->setEnabled(enabled);
}

void AddLanguageDialog::onSelectionChanged(const QItemSelection &selected,
                           const QItemSelection &deselected) {
   QModelIndexList selectedRows = ui->tableView->selectionModel()->selectedRows();

   for (const QModelIndex &index : selectedRows) {
       int row = index.row();
       qDebug() << "Selected row:" << row;
        if (row >= 0) {
            setConfirmEnable(true);
            break;
        }
   }
}


AddLanguageDialog::~AddLanguageDialog()
{
    delete ui;
}

void AddLanguageDialog::initCompleter()
{
    connect(mSearchLineEdit, &KSearchLineEdit::textChanged, this, [=](QString text){
        mSearchLineEdit->completer()->popup()->setVisible(false);
        m_proxyModel->setFilterRole(Qt::UserRole);
        m_proxyModel->setFilterRegExp(text);
    });
}

void AddLanguageDialog::showEvent(QShowEvent *e)
{
    mSearchLineEdit->clear();
    ui->tableView->clearSelection();
    QDialog::showEvent(e);
}

void AddLanguageDialog::initDict()
{
    if (!dict.isEmpty()) {
        return;
    }
    dict.reserve(25333);
    QFile file(kDictFile);

    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }
    QByteArray content = file.readAll();
    file.close();
    QTextStream stream(&content, QIODevice::ReadOnly);

    while (!stream.atEnd()) {
        const QString line = stream.readLine();
        const QStringList items = line.split(QChar(':'));

        if (items.size() == 2) {
            dict.insert(items[0].toInt(nullptr, 16), items[1]);
        }
    }
}

QString AddLanguageDialog::chineseToPinyin(const QString &words)
{
    QString result = "";
    if (words.contains(QRegExp("[\\x4e00-\\x9fa5]+"))) { //有中文
        for (int i = 0; i < words.length(); ++i) {
            const uint key = words.at(i).unicode();
            auto find_result = dict.find(key);

            if (find_result != dict.end()) {
                result.append(find_result.value());
            } else {
                result.append(words.at(i));
            }
        }
    }
    result = removeDigital(result);
    result.replace("cangyu", "zangyu");
    return result;
}

QString AddLanguageDialog::removeDigital(QString input)
{
    if ("" == input) {
        return "";
    }
    QString value = "";
    QByteArray ba = input.toLocal8Bit();
    char *data = nullptr;
    data = ba.data();
    while (*data) {
        if (!(*data >= '0' && *data <= '9')) {
            value += *data;
        }
        data++;
    }
    return value;
}

void AddLanguageDialog::setRowFlags(const QString &languageName, bool flag) {
    for (int row = 0; row < mode->rowCount(); ++row) {
        QModelIndex index = mode->index(row, 0);
        if (index.data().toString() == languageName) {
            QStandardItem* item = mode->itemFromIndex(index);
            if (flag) {
                item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled);
            } else {
                item->setFlags(item->flags() | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            }
            break;
        }
    }
}

void AddLanguageDialog::addRow(const QString &languageName, bool isAdded)
{
    QStandardItem* item = new QStandardItem(languageName);
    if (isAdded) {
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled);
    }
    mode->appendRow(item);
    mode->setData(mode->index(mode->rowCount() - 1, 0),
                  languageName + chineseToPinyin(languageName),
                  Qt::UserRole);
}
