/* -*- 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 "addshortcutdialog.h"
#include "realizeshortcutwheel.h"
#include <QApplication>
#include <glib.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <QFileSystemWatcher>
#include <kysdk/applications/accessinfohelper.h>
using namespace kdk;

#define DEFAULTPATH "/usr/share/applications/"

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);

AddShortcutDialog::AddShortcutDialog(QList<KeyEntry> generalEntries,
                                     QList<KeyEntry> windowEntries,
                                     QList<KeyEntry> customEntries, QWidget *parent) :
    KDialog(parent),
    gsPath(""),
    m_systemEntry(generalEntries),
    m_windowEntry(windowEntries),
    m_customEntry(customEntries),
    keyIsAvailable(false) {

    initUi();

    editSeq  = QKeySequence("");
    editName = "";
    keyIsAvailable  = 0;
    execIsAvailable = false;
    nameIsAvailable = false;
    execIcon = new QLabel(m_execLineEdit);
    execIcon->move(execIcon->x() + 8, execIcon->y());
    execIcon->setFixedSize(24, 36);
    m_execLineEdit->setTextMargins(32, m_execLineEdit->textMargins().top(),\
                                        m_execLineEdit->textMargins().right(),\
                                        m_execLineEdit->textMargins().bottom());
    initSetup();
    slotsSetup();
    limitInput();

}

AddShortcutDialog::~AddShortcutDialog()
{
}

void AddShortcutDialog::initUi() {
    setWindowIcon("ukui-control-center");
    setFixedSize(480, 286);

    m_execLabel = new KLabel(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_execLabel, "Shortcut", "addDialogExecLabel", "exec label of addShortcutDialog");
    m_execLabel->setText(tr("Exec"));
    m_execLabel->setObjectName(QString::fromUtf8("m_execLabel"));
    QSizePolicy sizePolicy1(QSizePolicy::Fixed, QSizePolicy::Fixed);
    sizePolicy1.setHorizontalStretch(0);
    sizePolicy1.setVerticalStretch(0);
    sizePolicy1.setHeightForWidth(m_execLabel->sizePolicy().hasHeightForWidth());
    m_execLabel->setSizePolicy(sizePolicy1);
    m_execLabel->setMinimumSize(QSize(48, 0));
    m_execLabel->setMaximumSize(QSize(48, 16777215));

    m_execLineEdit = new QLineEdit(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_execLineEdit, "Shortcut", "addDialogLineEdit", "exec lineedit of addShortcutDialog");
    m_execLineEdit->setObjectName(QString::fromUtf8("m_execLineEdit"));
    m_execLineEdit->setMinimumSize(QSize(160, 0));
    m_execLineEdit->setMaximumSize(QSize(16777215, 16777215));

    m_openBtn = new kdk::KPushButton(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_openBtn, "Shortcut", "addDialogOpenButton", "open button of addShortcutDialog");
    m_openBtn->setText(tr("Open"));
    m_openBtn->setObjectName(QString::fromUtf8("m_openBtn"));
    m_openBtn->setMinimumSize(QSize(84, 0));
    m_openBtn->setMaximumSize(QSize(84, 16777215));
    m_openBtn->setFocusPolicy(Qt::NoFocus);

    m_execHorizontalLayout = new QHBoxLayout();
    m_execHorizontalLayout->setSpacing(8);
    m_execHorizontalLayout->setObjectName(QString::fromUtf8("m_execHorizontalLayout"));
    m_execHorizontalLayout->addWidget(m_execLabel);
    m_execHorizontalLayout->addWidget(m_execLineEdit);
    m_execHorizontalLayout->addWidget(m_openBtn);

    verticalLayout = new QVBoxLayout();
    verticalLayout->setSpacing(0);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->addLayout(m_execHorizontalLayout);
    verticalSpacer = new QSpacerItem(20, 24, QSizePolicy::Minimum, QSizePolicy::Fixed);
    verticalLayout->addItem(verticalSpacer);

    m_nameLabel = new KLabel(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_nameLabel, "Shortcut", "addDialogNameLabel", "name label of addShortcutDialog");
    m_nameLabel->setText(tr("Name"));
    m_nameLabel->setObjectName(QString::fromUtf8("m_nameLabel"));
    sizePolicy1.setHeightForWidth(m_nameLabel->sizePolicy().hasHeightForWidth());
    m_nameLabel->setSizePolicy(sizePolicy1);
    m_nameLabel->setMinimumSize(QSize(48, 0));
    m_nameLabel->setMaximumSize(QSize(48, 16777215));

    m_nameLineEdit = new QLineEdit(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_nameLineEdit, "Shortcut", "addDialogNameLineEdit", "name lineedit of addShortcutDialog");
    m_nameLineEdit->setObjectName(QString::fromUtf8("m_nameLineEdit"));
    m_nameLineEdit->setMinimumSize(QSize(16, 0));
    m_nameLineEdit->setMaximumSize(QSize(16777215, 16777215));

    m_nameHorizontalLayout = new QHBoxLayout();
    m_nameHorizontalLayout->setSpacing(8);
    m_nameHorizontalLayout->setObjectName(QString::fromUtf8("m_nameHorizontalLayout"));
    m_nameHorizontalLayout->addWidget(m_nameLabel);
    m_nameHorizontalLayout->addWidget(m_nameLineEdit);
    verticalLayout->addLayout(m_nameHorizontalLayout);

    m_infoLabel = new QLabel(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_infoLabel, "Shortcut", "addDialogTipLabel", "tip label of addShortcutDialog");
    m_infoLabel->setText(tr("TextLabel"));
    m_infoLabel->setObjectName(QString::fromUtf8("m_infoLabel"));
    m_infoLabel->setMinimumSize(QSize(0, 24));
    m_infoLabel->setMaximumSize(QSize(16777215, 24));

    m_infoHorizontalLayout = new QHBoxLayout();
    m_infoHorizontalLayout->setSpacing(0);
    m_infoHorizontalLayout->setObjectName(QString::fromUtf8("m_infoHorizontalLayout"));
    m_infoHorizontalLayout->setContentsMargins(64, 0, -1, -1);
    m_infoHorizontalLayout->addWidget(m_infoLabel);
    verticalLayout->addLayout(m_infoHorizontalLayout);

    m_keyLabel = new KLabel(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_keyLabel, "Shortcut", "addDialogCancelButton", "tip label1 of addShortcutDialog");
    m_keyLabel->setText(tr("Key"));
    m_keyLabel->setObjectName(QString::fromUtf8("m_keyLabel"));
    m_keyLabel->setMinimumSize(QSize(48, 0));
    m_keyLabel->setMaximumSize(QSize(48, 16777215));

    m_keyHorizontalLayout = new QHBoxLayout();
    m_keyHorizontalLayout->setSpacing(8);
    m_keyHorizontalLayout->setObjectName(QString::fromUtf8("m_keyHorizontalLayout"));
    m_keyHorizontalLayout->addWidget(m_keyLabel);
    verticalLayout->addLayout(m_keyHorizontalLayout);

    m_verticalLayout1 = new QVBoxLayout();
    m_verticalLayout1->setSpacing(0);
    m_verticalLayout1->setObjectName(QString::fromUtf8("m_verticalLayout1"));
    m_verticalLayout1->setContentsMargins(0, 0, 0, 0);
    m_verticalLayout1->addLayout(verticalLayout);

    m_verticalLayout2 = new QVBoxLayout();
    m_verticalLayout2->setSpacing(16);
    m_verticalLayout2->setObjectName(QString::fromUtf8("m_verticalLayout2"));
    m_verticalLayout2->addLayout(m_verticalLayout1);

    wWidget = new QWidget(this);
    wWidget->setObjectName(QString::fromUtf8("wWidget"));
    wWidget->setMinimumSize(QSize(0, 24));
    wWidget->setMaximumSize(QSize(16777215, 24));

    m_info2Label = new QLabel(wWidget);
    KDK_EXTEND_ALL_INFO_FORMAT(m_info2Label, "Shortcut", "addDialogCancelButton", "tip label2 of addShortcutDialog");
    m_info2Label->setText(tr("TextLabel"));
    m_info2Label->setObjectName(QString::fromUtf8("m_info2Label"));

    m_info2HorizontalLayout = new QHBoxLayout(wWidget);
    m_info2HorizontalLayout->setSpacing(0);
    m_info2HorizontalLayout->setObjectName(QString::fromUtf8("m_info2HorizontalLayout"));
    m_info2HorizontalLayout->setContentsMargins(63, 0, 0, 0);
    m_info2HorizontalLayout->addWidget(m_info2Label);

    m_verticalLayout3 = new QVBoxLayout(this);
    m_verticalLayout3->setSpacing(0);
    m_verticalLayout3->setObjectName(QString::fromUtf8("m_verticalLayout3"));
    m_verticalLayout3->setContentsMargins(24, 8, 24, 16);
    m_verticalLayout3->addLayout(m_verticalLayout2);
    m_verticalLayout3->addWidget(wWidget);

    m_cancelBtn = new kdk::KPushButton(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_cancelBtn, "Shortcut", "addDialogCancelButton", "cancel button of addShortcutDialog");
    m_cancelBtn->setText(tr("Cancel"));
    m_cancelBtn->setObjectName(QString::fromUtf8("m_cancelBtn"));
    m_cancelBtn->setMinimumSize(QSize(96, 0));
    m_cancelBtn->setMaximumSize(QSize(96, 16777215));
    m_cancelBtn->setFocusPolicy(Qt::NoFocus);

    m_certainBtn = new kdk::KPushButton(this);
    KDK_EXTEND_ALL_INFO_FORMAT(m_certainBtn, "Shortcut", "addDialogCertainButton", "certain button of addShortcutDialog");
    m_certainBtn->setText(tr("Save"));
    m_certainBtn->setObjectName(QString::fromUtf8("m_certainBtn"));
    m_certainBtn->setMinimumSize(QSize(96, 0));
    m_certainBtn->setMaximumSize(QSize(16777215, 16777215));
    m_certainBtn->setCheckable(true);

    m_bottomHorizontalLayout = new QHBoxLayout();
    m_bottomHorizontalLayout->setSpacing(8);
    m_bottomHorizontalLayout->setObjectName(QString::fromUtf8("m_bottomHorizontalLayout"));
    m_bottomHorizontalLayout->setContentsMargins(-1, 16, -1, 8);
    horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_bottomHorizontalLayout->addItem(horizontalSpacer_2);
    m_bottomHorizontalLayout->addWidget(m_cancelBtn);
    m_bottomHorizontalLayout->addWidget(m_certainBtn);

    m_verticalLayout3->addLayout(m_bottomHorizontalLayout);
    mainWidget()->setLayout(m_verticalLayout3);
}

void AddShortcutDialog::initSetup()
{
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowTitle(tr("Add Shortcut"));

    m_execLineEdit->setReadOnly(true);

    m_info2Label->setStyleSheet("color: red; font-size: 14px;");
    m_infoLabel->setStyleSheet("color: red; font-size: 14px;");
    m_info2Label->setText("");
    m_infoLabel->setText("");
    m_certainBtn->setDisabled(true);
    m_certainBtn->setBackgroundColorHighlight(true);
    m_shortcutLine = new ShortcutLine(m_systemEntry, m_windowEntry, m_customEntry);
    m_shortcutLine->setAddDialogEdit(true);
    m_shortcutLine->setAttribute(Qt::WA_InputMethodEnabled, false);
    m_keyHorizontalLayout->addWidget(m_shortcutLine);
    m_shortcutLine->setMinimumWidth(280);
    m_shortcutLine->setPlaceholderText(tr("Please enter a shortcut"));

    m_shortcutLine->installEventFilter(this);

    m_nameLineEdit->installEventFilter(this);
    static const int MAX_LENGTH = 256;
    m_nameLineEdit->setMaxLength(MAX_LENGTH);
    connect(m_shortcutLine, &ShortcutLine::shortCutAvailable, this, [=](const int &flag) {
        shortCutAvailableSlot(flag);
    });

    if (m_shortcutLine->sizeHint().height() > 30 && m_shortcutLine->sizeHint().height() < 40) {
        this->setFixedHeight(286);
    } else if (m_shortcutLine->sizeHint().height() >= 40 && m_shortcutLine->sizeHint().height() < 50) {
        this->setFixedHeight(334);
    }
}

void AddShortcutDialog::shortCutAvailableSlot(const int &flag) {
    if (flag == 0 || (flag == -2 && editSeq == m_shortcutLine->keySequence())) {  //快捷键正常
        keyIsAvailable = 3;
    } else if(flag == -2) { //快捷键冲突
        keyIsAvailable = 1;
    } else {               //快捷键不可用
        keyIsAvailable = 2;
    }
    qDebug() << Q_FUNC_INFO << "flag" << flag << "certainBtn isEnabled" << m_certainBtn->isEnabled();
    if (flag == 4 && m_certainBtn->isEnabled()) {
        m_certainBtn->clicked(true);
        m_certainBtn->setProperty("isImportant", true);
    } else {
        refreshCertainChecked(3);
    }
}

void AddShortcutDialog::slotsSetup()
{
    connect(m_openBtn, &QPushButton::clicked, [=](bool checked){
        Q_UNUSED(checked)
        openProgramFileDialog();
    });

    connect(m_execLineEdit, &QLineEdit::textChanged, [=](QString text){
        if (mExec.endsWith("desktop")
            || (!g_file_test(mExec.toLatin1().data(),
                             G_FILE_TEST_IS_DIR)
                && g_file_test(mExec.toLatin1().data(), G_FILE_TEST_IS_EXECUTABLE))) {
            execIsAvailable = true;
        } else {
            execIsAvailable = false;
        }

        refreshCertainChecked(1);
    });

    connect(m_nameLineEdit, &QLineEdit::textChanged, [=](){
        QStringList customName;
        QString text = m_nameLineEdit->text();
        if (text.isEmpty()) {
            nameIsAvailable = false;
        } else {
            if (m_customEntry.isEmpty()) {
                nameIsAvailable = true;
            } else {
                    for (KeyEntry& ckeyEntry : m_customEntry) {
                        customName << ckeyEntry.nameStr;
                        if (customName.contains(text) && text != editName) {
                            nameIsAvailable = false;
                        } else {
                            nameIsAvailable = true;
                        }
                    }
            }
        }
        refreshCertainChecked(2);
    });

    connect(m_cancelBtn, &QPushButton::clicked, [=] {
        close();
    });
    connect(m_certainBtn, &QPushButton::clicked, [=] {
        qDebug() << Q_FUNC_INFO << gsPath << m_nameLineEdit->text() << selectedfile << m_shortcutLine->keySequence().toString();
        emit shortcutInfoSignal(gsPath, m_nameLineEdit->text(), selectedfile,
                                m_shortcutLine->keySequence().toString());

        close();
    });

    connect(this, &AddShortcutDialog::finished, [=] {
        gsPath = "";
        m_nameLineEdit->clear();
        m_execLineEdit->clear();
        m_nameLineEdit->setFocus(Qt::ActiveWindowFocusReason);
    });
}

void AddShortcutDialog::setTitleText(QString text)
{

}

void AddShortcutDialog::setUpdateEnv(QString path, QString name, QString exec)
{
    gsPath = path;
    m_nameLineEdit->setText(name);
    m_execLineEdit->setText(exec);
}

void AddShortcutDialog::limitInput()
{
    // 大小写字母数字中文
    QRegExp rx("[a-zA-Z0-9\u4e00-\u9fa5]+");
    QRegExpValidator *regValidator = new QRegExpValidator(rx);
    // 输入限制
    // m_nameLineEdit->setValidator(regValidator);
    // 字符长度限制
    // m_nameLineEdit->setMaxLength(10);
}

QString AddShortcutDialog::keyToSequence(QString key) {
    QString oldKey = key;
    key.replace(" ", "");
    if (key.contains("Win")) {
        key.replace("Win", "Meta");
    }

    if (key.contains("Super")) {
        key.replace("Super", "Meta");
    }

    if (key.contains("Start")) {
        key.replace("Start", "Meta");
    }
    if (key.contains("<")) {
        key.replace("<", "");
    }

    if (key.contains(">")) {
        key.replace(">", "+");
    }
    qDebug() << Q_FUNC_INFO << "update" << oldKey << "to" << key;
    return key;
}

QString AddShortcutDialog::keyToLib(QString key)
{
    if (key.contains("+")) {
        QStringList keys = key.split("+");
        if (keys.count() == 2) {
            QString lower = keys.at(1);
            QString keyToLib = "<" + keys.at(0) + ">" + lower.toLower();

            return keyToLib;
        } else if (keys.count() == 3) {
            QString lower = keys.at(2);
            QString keyToLib = "<" + keys.at(0) + ">" + "<" + keys.at(1) + ">" + lower.toLower();

            return keyToLib;
        } else if (keys.count() == 4) {
            QString lower = keys.at(2);
            QString keyToLib = "<" + keys.at(0) + ">" + "<" + keys.at(1) + ">" +  "<" + keys.at(2) + ">" + lower.toLower();

            return keyToLib;
        }
    }

    return key;
}

void AddShortcutDialog::openProgramFileDialog()
{
    QString filters = tr("Desktop files(*)");
    QFileDialog fd(this);

    QList<QUrl> usb_list = fd.sidebarUrls();
    int sidebarNum = 8;// 最大添加U盘数，可以自己定义
    QString home_path = QDir::homePath().section("/", -1, -1);
    QString mnt = "/media/" + home_path + "/";
    QDir mntDir(mnt);
    mntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList file_list = mntDir.entryInfoList();
    QList<QUrl> mntUrlList;
    for (int i = 0; i < sidebarNum && i < file_list.size(); ++i) {
        QFileInfo fi = file_list.at(i);
        mntUrlList << QUrl("file://" + fi.filePath());
    }

    QFileSystemWatcher m_fileSystemWatcher(&fd);
    m_fileSystemWatcher.addPath("/media/" + home_path + "/");
    connect(&m_fileSystemWatcher, &QFileSystemWatcher::directoryChanged, &fd,
            [=, &sidebarNum, &mntUrlList, &usb_list, &fd](const QString path) {
        QDir m_wmntDir(path);
        m_wmntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList m_wfilist = m_wmntDir.entryInfoList();
        mntUrlList.clear();
        for (int i = 0; i < sidebarNum && i < m_wfilist.size(); ++i) {
            QFileInfo m_fi = m_wfilist.at(i);
            mntUrlList << QUrl("file://" + m_fi.filePath());
        }
        fd.setSidebarUrls(usb_list + mntUrlList);
        fd.update();
    });

    connect(&fd, &QFileDialog::finished, &fd, [=, &usb_list, &fd]() {
        fd.setSidebarUrls(usb_list);
    });

    fd.setDirectory(DEFAULTPATH);
    fd.setAcceptMode(QFileDialog::AcceptOpen);
    fd.setViewMode(QFileDialog::List);
    fd.setNameFilter(filters);
    fd.setFileMode(QFileDialog::ExistingFile);
    fd.setWindowTitle(tr("select desktop"));
    fd.setLabelText(QFileDialog::Reject, tr("Cancel"));
    fd.setSidebarUrls(usb_list + mntUrlList);

    if (fd.exec() != QDialog::Accepted)
        return;

    selectedfile = fd.selectedFiles().first();

    QString exec = selectedfile.section("/", -1, -1);

    GDesktopAppInfo * textinfo = g_desktop_app_info_new_from_filename(selectedfile.toUtf8().constData());
    QString appname = g_app_info_get_name(G_APP_INFO(textinfo));
    const char * iconname = g_icon_to_string(g_app_info_get_icon(G_APP_INFO(textinfo)));
    setIcon(QString(QLatin1String(iconname)));

    mExec = exec;
    m_execLineEdit->setText(appname);
    m_nameLineEdit->setText(appname);
}

void AddShortcutDialog::refreshCertainChecked(int triggerFlag)
{
    if (!m_nameLineEdit->text().isEmpty()) {
        m_infoLabel->setText("");
    }

    if (!m_shortcutLine->text().isEmpty()) {
        m_info2Label->setText("");
    }

    if (!execIsAvailable || keyIsAvailable != 3 || !nameIsAvailable) {
        m_certainBtn->setDisabled(true);
        m_certainBtn->setProperty("isImportant", true);
        switch (triggerFlag) {
        case 1:
            if (!execIsAvailable) {
                m_info2Label->setText(tr("Invalid application"));  //程序无效
            } else if (keyIsAvailable == 1 && !m_shortcutLine->text().isEmpty()) {
                m_info2Label->setText(tr("Shortcut conflict"));  //快捷键冲突
            } else if (keyIsAvailable == 2 && !m_shortcutLine->text().isEmpty()) {
                m_info2Label->setText(tr("Invalid shortcut"));  //快捷键无效
            }
            if (!nameIsAvailable && !m_nameLineEdit->text().isEmpty()) {
                m_infoLabel->setText(tr("Name repetition"));  //名称重复
            }
            break;
        case 2:
            if (!nameIsAvailable && !m_nameLineEdit->text().isEmpty()) {
                m_infoLabel->setText(tr("Name repetition"));  //名称重复
            }
            if (keyIsAvailable == 1 && !m_shortcutLine->text().isEmpty()) {
                m_info2Label->setText(tr("Shortcut conflict"));  //快捷键冲突
            } else if (keyIsAvailable == 2 && !m_shortcutLine->text().isEmpty()) {
                m_info2Label->setText(tr("Invalid shortcut"));  //快捷键无效
            } else if (!execIsAvailable && !m_execLineEdit->text().isEmpty()) {
                m_info2Label->setText(tr("Invalid application"));  //程序无效
            }
            break;
        case 3:
            if (keyIsAvailable == 1) {
                m_info2Label->setText(tr("Shortcut conflict"));  //快捷键冲突
            } else if (keyIsAvailable == 2) {
                m_info2Label->setText(tr("Invalid shortcut"));  //快捷键无效
            } else if (!execIsAvailable && !m_execLineEdit->text().isEmpty()) {
                m_info2Label->setText(tr("Invalid application"));  //程序无效
            }
            if (!nameIsAvailable && !m_nameLineEdit->text().isEmpty()) {
                m_infoLabel->setText(tr("Name repetition"));  //名称重复
            }
            break;
        default:
            m_info2Label->setText(tr("Unknown error"));  //未知问题，不会触发
            break;
        }

    } else {
        m_certainBtn->setDisabled(false);
        qDebug() << Q_FUNC_INFO << "certainBtn setDisabled" << m_certainBtn->isEnabled();
    }
}

bool AddShortcutDialog::conflictWithGlobalShortcuts(const QKeySequence &keySequence)
{
    QHash<QKeySequence, QList<KGlobalShortcutInfo>> clashing;
    for (int i = 0; i < keySequence.count(); ++i) {
        QKeySequence keys(keySequence[i]);

        if (!KGlobalAccel::isGlobalShortcutAvailable(keySequence)) {
            clashing.insert(keySequence, KGlobalAccel::getGlobalShortcutsByKey(keys));
        }
    }

    if (clashing.isEmpty()) {
        return false;
    } else {
        qDebug() << "conflict With Global Shortcuts";
    }

    return true;
}

bool AddShortcutDialog::conflictWithStandardShortcuts(const QKeySequence &seq)
{
    KStandardShortcut::StandardShortcut ssc = KStandardShortcut::find(seq);
    if (ssc != KStandardShortcut::AccelNone) {
        qDebug() << "conflict With Standard Shortcuts";
        return true;
    }

    return false;
}

bool AddShortcutDialog::conflictWithSystemShortcuts(const QKeySequence &seq)
{
    QString systemKeyStr = keyToLib(seq.toString());

    if (systemKeyStr.contains("Ctrl")) {
        systemKeyStr.replace("Ctrl", "Control");
    }
    for (KeyEntry& ckeyEntry : m_systemEntry) {
        if (systemKeyStr == ckeyEntry.valueStr) {
            qDebug() << "conflictWithSystemShortcuts" << seq;
            return true;
        }
    }
    return false;
}

bool AddShortcutDialog::conflictWithCustomShortcuts(const QKeySequence &seq)
{
    QString customKeyStr = keyToLib(seq.toString());

    for (KeyEntry& ckeyEntry : m_customEntry) {
        if (customKeyStr == ckeyEntry.bindingStr) {
            qDebug() << "conflictWithCustomShortcuts" << seq;
            return true;
        }
    }
    return false;
}

bool AddShortcutDialog::isKeyAvailable(const QKeySequence &seq)
{
    QString keyStr = seq.toString();

    if (!keyStr.contains("+")) {
        qDebug() << "is not Available";
        return false;
    } else if (keyStr.contains("Num") || keyStr.contains("Space")
               || keyStr.contains("Meta") || keyStr.contains("Ins") || keyStr.contains("Home")
               || keyStr.contains("PgUp") || keyStr.contains("Del") || keyStr.contains("End")
               || keyStr.contains("PgDown") || keyStr.contains("Print")
               || keyStr.contains("Backspace") || keyStr.contains("ScrollLock")
               || keyStr.contains("Return") || keyStr.contains("Enter")
               || keyStr.contains("Tab") || keyStr.contains("CapsLock")
               || keyStr.contains("Left") || keyStr.contains("Right")
               || keyStr.contains("Up") || keyStr.contains("Down")
               || keyStr.contains("Clear Grab")) {
        qDebug() << "is not Available";
        return false;
    } else {
        QStringList keys = keyStr.split("+");
        if (keys.count() == 4) {
            qDebug() << "is not Available";
            return false;
        } else {
            QString key = keys.at(keys.count() - 1);
            if (!key.contains(QRegExp("[A-Z]")) && !key.contains(QRegExp("[a-z]"))
                && !key.contains(QRegExp("[0-9]"))) {
                qDebug() << "is not Available";
                return false;
            }
        }
    }

    return true;
}

void AddShortcutDialog::setExecText(const QString &text)
{
    selectedfile = text;
    QString exec = selectedfile.section("/", -1, -1);

    GDesktopAppInfo * textinfo = g_desktop_app_info_new_from_filename(selectedfile.toUtf8().constData());
    QString appname = g_app_info_get_name(G_APP_INFO(textinfo));
    const char * iconname = g_icon_to_string(g_app_info_get_icon(G_APP_INFO(textinfo)));
    setIcon(QString(QLatin1String(iconname)));

    mExec = exec;
    m_execLineEdit->setText(appname);
}

void AddShortcutDialog::setNameText(const QString &text)
{
    editName = text;
    m_nameLineEdit->setText(text);
}

void AddShortcutDialog::setKeyText(const QString &text)
{
    QString showText = text;
    showText = showText.replace("<","");
    showText = showText.replace(">"," + ");
    QString endStr = showText.mid(showText.length() - 1, 1);
    if (showText != tr("Null") && showText != "Null" && showText != "") {
        showText = showText.mid(0, showText.length() - 1) + endStr.toUpper();
    } else {
        showText = tr("Null");
    }
    QString newShowText = showText;
    if (newShowText.contains(" + ")) {
        newShowText.replace("+", " ");
    }
    if (newShowText.contains("Win")) {
        newShowText.replace("Win", "Super");
    }
    m_shortcutLine->setText(newShowText.replace("+", "   "));
    if (showText.contains("Win")) {
        showText.replace("Win", "meta");
    }
    if (showText.contains("Super")) {
        showText.replace("Super", "meta");
    }
    qDebug() << Q_FUNC_INFO << text << showText << newShowText;
    QString toSeq = keyToSequence(showText);
    QKeySequence seq(toSeq);
    editSeq = seq;
    m_shortcutLine->setKeySequence(seq);
    qDebug() << Q_FUNC_INFO << "key" << toSeq << "to KeySequence" << m_shortcutLine->keySequence().toString();
}

void AddShortcutDialog::setSourceEnable(bool enabled) {
    m_openBtn->setEnabled(enabled);
}

void AddShortcutDialog::setKeyIsAvailable(const int key) {
    keyIsAvailable = key;
}

void AddShortcutDialog::setIcon(const QString &iconname)
{
    QString iconPath = iconname;
    QFileInfo iconFile = QFileInfo(iconPath);
    QIcon appicon;

    if (appicon.hasThemeIcon(iconname)) {
        appicon = QIcon::fromTheme(iconname);
        execIcon->setPixmap(QPixmap::fromImage(appicon.pixmap(24,24).toImage()));
    } else {
        if (!iconFile.exists()) {
            iconPath  = QString("/usr/share/pixmaps/" + iconname + ".png");
            iconFile = QFileInfo(iconPath);
            if (!iconFile.exists()) {
                iconPath = QString(":/img/plugins/autoboot/desktop.png");
            }
        }
        execIcon->setPixmap(QPixmap(iconPath).scaled(QSize(24,24), Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    }
}

bool AddShortcutDialog::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::FocusOut) {
        if (o == m_shortcutLine) {
            if (m_shortcutLine->text().isEmpty()) {
                m_info2Label->setText(tr("Shortcut cannot be empty"));
            }
        } else if (o == m_nameLineEdit) {
            if (m_nameLineEdit->text().isEmpty()) {
                m_infoLabel->setText(tr("Name cannot be empty"));
            }
        }
    } else if (e->type() == QEvent::Resize) {
        if (o == m_shortcutLine) {
            if (m_shortcutLine->sizeHint().height() > 30 && m_shortcutLine->sizeHint().height() < 40) {
                this->setFixedHeight(286);
            } else if (m_shortcutLine->sizeHint().height() >= 40 && m_shortcutLine->sizeHint().height() < 50) {
                this->setFixedHeight(334);
            }
        }
    }
    return KDialog::eventFilter(o, e);
}
