#include "qaptdownloaddeb.h"
#include <QDebug>
#include <QMessageBox>
#include <QThread>
#include <QApplication>
#include <ukui-log4qt.h>
QAptDownLoadDeb::QAptDownLoadDeb(QWidget *parent)
{
    initQaptBackend();
}

void QAptDownLoadDeb::initQaptBackend()
{
    auto *initThread = QThread::create([this](){
        m_backend = new QApt::Backend(this);
        if(!m_backend->init()){
            QMessageBox::warning(nullptr,tr("Tips"),tr("Backend init failed"));
        }
        qaptInited = true;
    });
    initThread->start();
}

void QAptDownLoadDeb::updateLabels()
{
    m_package = m_backend->package("mesa-utils");//包名
    QString timeString  =m_package->supportedUntil().toString();
    QMessageBox::warning(nullptr,"提示",timeString);
    QApt::PackageList searchList = m_backend->search("mesa-utils");
    if(searchList.isEmpty())
    {
        QMessageBox::warning(nullptr,"提示","当前未找到该安装包，无法下载");
    }
    foreach (QApt::Package *pkg, searchList) {
        QMessageBox::warning(nullptr,("11111111111111111111"),(pkg->name()));
    }
}

bool QAptDownLoadDeb::updateCache()
{
     m_trans = m_backend->updateCache();
     if(m_trans)
     {
         m_trans->run();
         return true;
     }else
     {
         return false;
     }
}

bool QAptDownLoadDeb::startInstall(QString filePath, QString debName)
{

}

bool QAptDownLoadDeb::startDownload(QString &packageName)
{
    m_package = m_backend->package(packageName);
    if(!m_package)
    {
       QString tips = QString(tr("%1 package not founds")).arg(packageName);
       QMessageBox::warning(nullptr,tr("Tips"),tips);
       KyInfo() << "package not founds";
       return false ;
    }
//    //判断是否已经安装
//    if(m_package->isInstalled())
//    {
//        QMessageBox::warning(nullptr,tr("tips"),tr("current package is installed"));
//        return false;
//    }
//    m_package->setInstall();
//    m_trans = m_backend->commitChanges();

    QString searchList = "/home/kylin/DownloadDemo/debName.txt";
    QString dirPath  = "/home/kylin/DownloadDemo/download_deb";
    m_trans = m_backend->downloadArchives(searchList,dirPath);
    if (!m_trans) {
        QMessageBox::warning(nullptr,tr("Tips"),tr("Failed to create transaction."));
        KyInfo() << "Failed to create transaction.";
        return false ;
    }
//    m_trans->setProxy("http");
//    m_trans->setLocale(QLatin1String(setlocale(LC_MESSAGES, 0)));

    connect(m_trans, SIGNAL(statusChanged(QApt::TransactionStatus)),
            this, SLOT(onTransactionStatusChanged(QApt::TransactionStatus)));
    connect(m_trans,SIGNAL(progressChanged(int)),this,SLOT(onTransactionProgressChanged(int)));
    connect(m_trans,&QApt::Transaction::progressChanged,this,[&](int value ){
           emit sigCurrentProgressValue(value);
    });
    connect(m_trans,&QApt::Transaction::downloadProgressChanged,this,&QAptDownLoadDeb::onDownloadProgressChanged);

    if(m_trans)
    {
        m_trans->run();
        return true;
    }
}

bool QAptDownLoadDeb::startCheckVersion(QString &packageName)
{
    m_package = m_backend->package(packageName);
    if(!m_package)
    {
        QString tip = QString("%1 package not founds").arg(packageName);
       QMessageBox::warning(nullptr,tr("Tips"),tip);
       KyInfo() << "package not founds";
       return false;
    }
    if(!m_package->isInstalled())
    {
        //QMessageBox::warning(nullptr,tr("tips"),tr("package could be install11."));
        KyInfo() << "Package " << packageName << " could be install.";
        return true;
    }
    if(m_package->isInUpdatePhase())
    {
        //QMessageBox::warning(nullptr,tr("tips"),tr("package could be update."));
        KyInfo() << "Package " << packageName << " could be update.";
        return true;
    }
    else {
         QMessageBox::warning(nullptr,tr("Tips"),tr("Package could not  be update."));
         KyInfo() << "Package " << packageName << " could not  be update.";
        return false;
    }
}

bool QAptDownLoadDeb::checkPkgVersion(QString pkgName)
{
    QString curVersion = getCurPkgVersion(pkgName);
    QString lastVersion = getLastestVersion(pkgName);
    if(curVersion == lastVersion || lastVersion.isEmpty())
    {
        QMessageBox::warning(nullptr,tr("Tips"),tr("The current model is already the latest model"));
        return true;
    }
    else{
        QMessageBox::warning(nullptr,tr("Tips"),tr("New version needs to be updated upon discovery"));
        return false;
    }
}

QString QAptDownLoadDeb::getCurPkgVersion(QString pkgName)
{
    while (!qaptInited) {
        qApp->processEvents();
        QThread::usleep(1);
    }
    auto package  = m_backend->package(pkgName);
    if(package == nullptr){
        return QString();
    }
    return package->version();
}

QString QAptDownLoadDeb::getLastestVersion(QString pkgName)
{
    while (!qaptInited) {
        qApp->processEvents();
        QThread::usleep(1);
    }
    auto updatePackageList = m_backend->upgradeablePackages();
    for (auto tmpPkg : updatePackageList) {
        if (tmpPkg->name() == pkgName) {
            return tmpPkg->availableVersion();
        }
    }
    return QString();
}

void QAptDownLoadDeb::onTransactionStatusChanged(QApt::TransactionStatus status)
{
    QString headerText;

       switch (status) {
       case QApt::RunningStatus:
           // For roles that start by downloading something, switch to download view
           if (m_trans->role() == (QApt::UpdateCacheRole || QApt::UpgradeSystemRole ||
                                   QApt::CommitChangesRole || QApt::DownloadArchivesRole ||
                                   QApt::InstallFileRole)) {
//               QMessageBox::warning(nullptr,tr("tips"),tr("11111111111111111111111."));
           }
           break;
       case QApt::DownloadingStatus:
//              QMessageBox::warning(nullptr,tr("tips"),tr("2222222222222222222222."));
           break;
       case QApt::CommittingStatus:
//              QMessageBox::warning(nullptr,tr("tips"),tr("3333333333333333333333."));
           break;
       case QApt::FinishedStatus:
           // FIXME: Determine which transactions need to reload cache on completion
           m_backend->reloadCache();
//           QMessageBox::warning(nullptr,tr("tips"),tr("4444444444444444444."));
           // Clean up transaction object
           m_trans->deleteLater();
           m_trans = 0;
           break;
       default:
           break;
       }
}

void QAptDownLoadDeb::onDownloadProgressChanged(QApt::DownloadProgress progress)
{
//        QMessageBox::warning(nullptr,tr("tips"),progress.uri());
}
