#include <QFileDialog>
#include "custom_message_box.h"

#include "find_and_match_ppds.h"
#include "ukui_apt.h"

#include "select_ppd_dialog.h"
#include "base_notify_dialog.h"
#include "choose_ppd_combo_box.h"

ChoosePpdComboBox::ChoosePpdComboBox(QWidget *parent)
    : CustomComboBox(parent)
{
    setParent(parent);
    setDefaultPreItem(tr("Choose PPD"), true);
    setDefaultAfterItem(tr("Choose from the PPD library"));
    setDefaultAfterItem(tr("Add local PPD"));
    connect(this, &QComboBox::currentTextChanged, [=](const QString &text) {
        if (text.isEmpty()) {
            return;
        }
        if (text == tr("Choose PPD")) {
            emit currentPpdChanged(true, text);
            setCurrentIndexToDefault();
        } else if (text == tr("Choose from the PPD library")) {
            emit currentPpdChanged(true, text);
            setCurrentIndexToDefault();
            showSelectPpdDialog();
        } else if (text == tr("Add local PPD")) {
            emit currentPpdChanged(true, text);
            setCurrentIndexToDefault();
            onChooseClicked();
        } else{
            emit currentPpdChanged(false, text);
        }
    });
}

ChoosePpdComboBox::~ChoosePpdComboBox()
{
}

void ChoosePpdComboBox::onChooseClicked()
{
qDebug() << __FUNCTION__;
    // Popup a new window to choose a valid driver
    QString debName = "";
    QFileDialog dialog(parentWidget() ,tr("Please select a deb package."));
    dialog.setFileMode(QFileDialog::AnyFile);
    dialog.setNameFilter(tr("Deb File(*.deb)"));
    dialog.setLabelText(QFileDialog::Accept, tr("Choose"));
    dialog.setLabelText(QFileDialog::Reject, tr("Cancel"));
    if(QDialog::Accepted == dialog.exec()){
      //  QStringList fileName = dialog.selectedFiles();
        QStringList names = dialog.selectedFiles();
        qDebug() << names;
        if(names.size()!=0) {
            debName = names.at(0);
        }
    }
    QPoint windowCenter = QPoint(parentWidget()->mapToGlobal(QPoint(0,0)).x() + parentWidget()->width()/2,parentWidget()->mapToGlobal(QPoint(0,0)).y() + parentWidget()->height()/2);
    //QString debName = QFileDialog::getOpenFileName(this, tr("Please select a deb package."), QDir::currentPath(), "Deb(*.deb)");
    if (debName.compare("") != 0) {
        //安装这个包
        m_installOk = -1;
        BaseNotifyDialog dialog;
        dialog.hide();
        dialog.dialogSetType(BaseNotifyDialogType::WAITTING);
        dialog.labelSetText(tr("Searching driver..."));
        dialog.show();
        dialog.move(windowCenter - dialog.rect().center());
        connect(g_findAndMatchWorkThread, &FindAndMatchPPDs::updateFinished, &dialog, &QDialog::close);
        connect(g_findAndMatchWorkThread, &FindAndMatchPPDs::updateFailed, &dialog, &QDialog::close);
        connect(this, SIGNAL(installEnd()), &dialog, SLOT(close()));

        DebUtilHelper* debHelper = new DebUtilHelper(debName);
        connect(debHelper, &DebUtilHelper::succeed, [=]() {
            qDebug() << "Install succeed";
            m_installOk = 0;
            g_findAndMatchWorkThread->updatePPDsMap();
        });
        connect(debHelper, &DebUtilHelper::failed, [=]() {
            qDebug() << "Install failed";
            m_installOk = 1;
            emit installEnd();
        });
        debHelper->startWorker();
        dialog.exec();
        if (m_installOk == 1) {
            //弹窗
            CustomMessageBox Msg(CustomMessageBox::Warning, tr("Warning"), tr("Install package failed，please retry."), CustomMessageBox::NoButton);
            QPushButton *btnYes = Msg.addButton(tr("Yes"), CustomMessageBox::YesRole);
            Msg.move(windowCenter - Msg.rect().center());
            Msg.exec();
            return;
        }
    } else {
        //弹窗
        CustomMessageBox Msg(CustomMessageBox::Warning, tr("Warning"), tr("No driver package selected,Continue?"), CustomMessageBox::NoButton);
        QPushButton *btnYes = Msg.addButton(tr("Confirm"), CustomMessageBox::YesRole);
        QPushButton *btnNo  = Msg.addButton(tr("Cancel"), CustomMessageBox::NoRole);
        Msg.move(windowCenter - Msg.rect().center());
        Msg.exec();
        setCurrentIndexToDefault();
        if ((QPushButton*)Msg.clickedButton() == btnNo) {
            return;
        }
    }
    showSelectPpdDialog();
}

void ChoosePpdComboBox::showSelectPpdDialog()
{
    //打开新窗口，返回一个String或啥也不返回
    m_retPpdName = "";
    QEventLoop eventloop;
    connect(this, SIGNAL(receivePPD()), &eventloop, SLOT(quit()));
    SelectPpdDialog* selectDialog = new SelectPpdDialog(parentWidget());
    connect(selectDialog, &SelectPpdDialog::chosenPPDName, [=](QString str) {
        qDebug() << str;
        m_retPpdName = str;
        emit receivePPD();
    });
    connect(selectDialog, &SelectPpdDialog::userCanceled, [=]() {
        qDebug("Cancel");
        emit receivePPD();
    });
    selectDialog->updateTableView();
    selectDialog->show();
    eventloop.exec();
    selectDialog->deleteLater();
    if (m_retPpdName.compare("") != 0) {
        //更新Combobox
        clear();
        addItem(m_retPpdName);
    }
}