/* -*- 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();
    ui->frame->layout()->addWidget(mSearchLineEdit);
    ui->tableView->setFrameShape(QFrame::Panel);
    mode = new QStandardItemModel(this);
    ui->tableView->setModel(mode);
    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);

    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());
        }
        Q_EMIT addShowLanguage(selectedLanguageList);
        this->hide();
    });

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

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

void AddLanguageDialog::initCompleter()
{
    QCompleter *m_completer = new QCompleter(this);
    m_completer->setModel(mode);
    m_completer->setMaxVisibleItems(6);
    m_completer->popup()->setAttribute(Qt::WA_InputMethodEnabled);
    m_completer->setFilterMode(Qt::MatchContains);
    m_completer->setCaseSensitivity(Qt::CaseInsensitive);
    m_completer->setCompletionRole(Qt::UserRole); //设置ItemDataRole
    m_completer->setWrapAround(false);
    if (mSearchLineEdit) {
        mSearchLineEdit->setCompleter(m_completer);
        mSearchLineEdit->reloadStyle();
    }

    connect(mSearchLineEdit, &KSearchLineEdit::returnPressed, this, [=]() {
        if (!mSearchLineEdit->text().isEmpty()) {
            QList<QStandardItem*> itemList = mode->findItems(mSearchLineEdit->text());
            if (!itemList.isEmpty()) {
                QModelIndex m_modeIndex = mode->indexFromItem(itemList.first());
                ui->tableView->scrollTo(m_modeIndex);
                int index = m_modeIndex.row();
                ui->tableView->selectRow(index);
            }
        }
    });

    connect(mSearchLineEdit, &KSearchLineEdit::textChanged, this, [=](QString text){
        for (int i = 0; i < mode->rowCount(); i++) {
            if (text.contains(mode->data(mode->index(i,0)).toString())) {
                mSearchLineEdit->blockSignals(true);
                mSearchLineEdit->setText(mode->item(i)->text());
                mSearchLineEdit->blockSignals(false);
            }
        }
    });

    connect(m_completer, QOverload<const QString &>::of(&QCompleter::activated),
            [=](const QString &text) {
        Q_UNUSED(text);
        Q_EMIT mSearchLineEdit->returnPressed();
    });
}

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::addRow(const QString &languageName)
{
    mode->appendRow(new QStandardItem(languageName));
    mode->setData(mode->index(mode->rowCount() - 1, 0),
                  languageName + chineseToPinyin(languageName),
                  Qt::UserRole);
}
