/*
 * Copyright (C) 2020, 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 3 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, see <https://www.gnu.org/licenses/>.
 */

#include <QEventLoop>
#include "ukui_printer.h"
#include "printer_check_helper.h"
#include "device_information.h"
#include "lpinfo_browser.h"
#include "package_helper.h"
#include "ukui_apt.h"
#include "find_ppd_worker.h"
#include "system_notification.h"

 PrinterCheckHelper::PrinterCheckHelper(const QString &printername)
{
    m_printername = printername;
}

PrinterCheckHelper::~PrinterCheckHelper()
{

}

void PrinterCheckHelper::dowork()
{
    qDebug() << "im in PrinterCheckHelper!";
    UkuiUsbPrinter selectPrinter = UkuiPrinterManager::getInstance().getPrinterFromName(m_printername); 

    if (selectPrinter.name.isEmpty() || selectPrinter.device_uri.isEmpty()) {
        finished();
        return;
    }

    if (selectPrinter.info == selectPrinter.name + " added by kylin-printer.") {
        finished();
        return;
    }

    DeviceInformation info = LpinfoBrowser::getDeviceFromUri(selectPrinter.device_uri);

    QEventLoop loop;
    PackageHelper* pkgHelper = new PackageHelper(info);
    m_needInstall = false;
    m_pkgHelperFlag = false;
    connect(pkgHelper, &PackageHelper::finished, &loop, &QEventLoop::quit);
    connect(pkgHelper, &PackageHelper::succeed, [=](bool needInstall) {
        m_needInstall = needInstall;
        pkgHelper->finished();
        m_pkgHelperFlag = true;
    });
    connect(pkgHelper, &PackageHelper::failed, [=]() {
        qDebug() << "Install failed";
        pkgHelper->finished();
        m_pkgHelperFlag = false;
    });
    pkgHelper->startWorker();
    loop.exec();

    if (!m_pkgHelperFlag) {
        qDebug () << "搜索驱动失败!";
        finished();
        return;
    }

    if (info.suggestPpdName.isEmpty()) {
        finished();
        return;
    }

    if (m_needInstall == true && !info.packageLevel.isEmpty() && info.packageLevel != "1") {
        QString tipStr;
        if (info.packageLevel == "2") {

        } else {
            finished();
            return;
        }
    }

    if (m_needInstall) {
        m_installOk = 1;
        QEventLoop loop;
        connect(this, &PrinterCheckHelper::installEnd, &loop, &QEventLoop::quit);
        AptUtilHelper *aptHelper = new AptUtilHelper(info);
        connect(aptHelper, &AptUtilHelper::succeed, [ = ]() {
            qDebug() << "Install succeed";
            m_installOk = 0;
            emit installEnd();
        });
        connect(aptHelper, &AptUtilHelper::failed, [ = ]() {
            qDebug() << "Install failed";
            m_installOk = 1;
            emit installEnd();
        });
        aptHelper->startWorker();
        loop.exec();
        aptHelper->finished();
        if (m_installOk == 1) {
            qDebug () << "安装驱动失败!";
            // finished();
            // return;
        }
    }

    QString ppd;
    QStringList ppdList;
    int ret;

    FindPpdWorker *worker = new FindPpdWorker();

    if (m_installOk == 0) {
        worker->setStatus(true);
    } else {
        worker->setStatus(false);
    }

    worker->setInput(info.vendor, info.model, info.suggestPpdName);

    QEventLoop loop2;
    connect(worker, &FindPpdWorker::finished, &loop2, &QEventLoop::quit);
    connect(worker, &FindPpdWorker::result, [=, &ret, &ppd, &ppdList](int res, QString exactMatchPPD, QStringList matchResultList) {
        ret = res;
        ppd = exactMatchPPD;
        ppdList = matchResultList;
        worker->finished();
    });

    worker->startWorker();
    loop2.exec();


    if (ret != 0) {
        qDebug() << ret;
    }

    if (ppd.isEmpty()) {
        finished();
        return;
    }

    QString oldmodelname = selectPrinter.make_and_model;

    QString errorString;
    ret = UkuiPrinterManager::getInstance().addPrinter(QString()
                                     ,m_printername,ppd
                                     ,selectPrinter.location, errorString);

    if (ret == false) {
        finished();
        return;
    }

    UkuiUsbPrinter newselectPrinter = UkuiPrinterManager::getInstance().getPrinterFromName(m_printername);


    if (newselectPrinter.name.isEmpty() || newselectPrinter.device_uri.isEmpty()) {
        finished();
        return;
    }

    if (oldmodelname == newselectPrinter.make_and_model) {
        finished();
        return;
    }

    // QString title = "完成打印机驱动修复";
    QString title = tr("Complete printer driver repair");
    // QString text = QString("“%1” 打印机驱动修复已完成").arg(m_printername);
    QString text = tr("\"%1\" Printer driver repair completed").arg(m_printername);
    SystemNotification().sendMessage(text, title, 5000);
}
