#include "page2.h"
#include<QMessageBox>
#include<QDBusMessage>
Page2::Page2(QWidget *parent) : QWidget(parent)
{
    round = new QRoundProgressBar(this);
  //  round->setBarStyle(QRoundProgressBar::StyleLine);
  //  round->setOutlinePenWidth(15);
  //  round->setDataPenWidth(5);
  //  round->setMinimum(0);
  //  round->setMaximum(100);
 //   round->setValue(0);
    round->setPersent(0);
    round->show();
    menu=new menuModule(this);

    lableMovie=new QLabel(this);
    QSize movieSize(95,95);
    round->setFixedSize(movieSize);
    lableMovie->setFixedSize(movieSize);
    lableMovie->hide();

    lableText=new QLabel;
    lableText->setWordWrap(true);
    lableText->setAlignment(Qt::AlignHCenter);


    QWidget *btnwidget=new QWidget(this);
    returnPushButton=new QPushButton(btnwidget);
    cancelbtn = new QPushButton(btnwidget);
    cancelbtn->setText(tr("Cancel"));
    //cancelbtn->setFixedSize(150,40);
    //connect(returnPushButton,&QPushButton::clicked,this,&Page2::returnMain);
    connect(cancelbtn,&QPushButton::clicked,this,&Page2::returnMain);
    connect(returnPushButton,&QPushButton::clicked,[=]{movieStatus = loading;});
    connect(menu,&menuModule::iconchange,this,&Page2::setIconchange);
  //  returnPushButton->setFixedSize(150,40);
    QLabel *filling1 = new QLabel;
    QLabel *filling2 = new QLabel;
    QLabel *filling3 = new QLabel;
    QLabel *filling4 = new QLabel;
    QLabel *filling5 = new QLabel;
    QLabel *filling6 = new QLabel;
    QHBoxLayout *hlt1=new QHBoxLayout;
    hlt1->setMargin(0);
    hlt1->setSpacing(0);
    hlt1->addWidget(filling1,9);
    hlt1->addWidget(lableMovie);
    hlt1->addWidget(round);
    hlt1->addWidget(filling2,9);
    QHBoxLayout *hlt2=new QHBoxLayout;
    hlt2->setMargin(0);
    hlt2->setSpacing(0);
    hlt2->addWidget(filling3,9);
    hlt2->addWidget(lableText);
    hlt2->addWidget(filling4,9);
    QHBoxLayout *hlt3=new QHBoxLayout;
    btnwidget->setLayout(hlt3);
    hlt3->setMargin(0);
    hlt3->setSpacing(0);
    hlt3->addWidget(filling5,9);
    hlt3->addWidget(cancelbtn);
    hlt3->addStretch(1);
    hlt3->addWidget(returnPushButton);
    hlt3->addWidget(filling6,9);
    filling6->show();
    QVBoxLayout *vlt1=new QVBoxLayout;
    vlt1->setMargin(0);
    vlt1->setSpacing(0);
    vlt1->addSpacing(115);
    vlt1->addLayout(hlt1);
    vlt1->addSpacing(26);
    vlt1->addLayout(hlt2);
    vlt1->addSpacing(220);
    vlt1->addWidget(btnwidget);
    vlt1->addStretch();
    this->setLayout(vlt1);
    connect(returnPushButton,&QPushButton::clicked,this,[=](){
        allclose();
    });
}
void Page2::makestar(QString path,QString sourcepath){
    isopath=path;
    usbpath=sourcepath;
}
void Page2::allclose(){
    if(returnPushButton->text()==tr("Retry")){
        QDBusMessage m = QDBusMessage::createMethodCall("com.kylinusbcreator.systemdbus","/",
                                                        "com.kylinusbcreator.interface","MakeStart");
        m<<isopath;
        m<<usbpath;
        QDBusConnection::systemBus().call(m);
        startMaking();
    }
    if(returnPushButton->text()==tr("Close")){
        emit mainclose();
    }
}
void Page2::playLoadingGif()
{
    returnPushButton->setEnabled(false);
    returnPushButton->setText(tr("In production"));
    cancelbtn->setText(tr("Cancel"));
    movieStatus = loading;
    round->show();
    lableMovie->hide();
    if(LIGHTTHEME == themeStatus)
    {
      //  setThemeStyleLight();
    }else{
      //  setThemeStyleDark();
    }
    lableText->setText(tr("Please do not remove the USB driver or power off now"));
}

void Page2::playFinishGif()
{
    round->hide();
    lableMovie->show();
    lableMovie->setScaledContents(true);
 //   lableMovie->setPixmap(QPixmap::fromImage(QImage(":/data/success.png")));
    lableMovie->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(96,96));
    returnPushButton->setEnabled(true);
    cancelbtn->setText(tr("Return"));
    returnPushButton->setText(tr("Close"));
    lableText->setText(tr("Finish"));
    lableMovie->clear();
    movieStatus = finish;
    if(themeStatus == DARKTHEME)
    {
        round->setPersent(0);
        //round->setValue(0);
      //  round->setFormat(0);
      //  lableMovie->setPixmap(QPixmap::fromImage(QImage(":/data/success.png")));
        lableMovie->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(96,96));
    }else
    {
      //  lableMovie->setPixmap(QPixmap::fromImage(QImage(":/data/success.png")));
        lableMovie->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(96,96));
    }
}

void Page2::playErrorGif()
{
    round->hide();
    returnPushButton->setEnabled(true);
    cancelbtn->setText(tr("Return"));
    returnPushButton->setText(tr("Retry"));
    movieStatus = failed;
    lableText->setText(tr("Creation Failed"));
    lableMovie->show();
    lableMovie->clear();
    lableMovie->setScaledContents(true);
    lableMovie->setPixmap(QIcon::fromTheme("dialog-error").pixmap(95,95));
  //  lableMovie->setPixmap(QPixmap::fromImage(QImage(":/data/elements_dark/failed.png")));
}

void Page2::startMaking()
{
    playLoadingGif();
    QDBusConnection::systemBus().connect(QString(),QString("/"),"com.kylinusbcreator.interface","workingProgress",this,SLOT(dealWorkingProgress(int)));
    QDBusConnection::systemBus().connect(QString(),QString("/"),"com.kylinusbcreator.interface","makeFinish",this,SLOT(dealMakeFinish(QString)));
}
void Page2::dealerrorstr(QString str){
//    qInfo()<<"errorstr"<<str;
//    if(str.isEmpty()){
//        playErrorGif();
//    }
}
void Page2::dealWorkingProgress(int progress){
    QString ii=QString::number(progress);
    if(ii.isEmpty()){
        return;
    }else{
    round->setPersent(progress);
    qInfo()<<"progress"<<progress;
    }
    //round->setValue(progress);
  //  round->setFormat(QString::number(progress)+"%");
}

void Page2::dealMakeFinish(QString status)
{
    uDiskPath = "";
    if("success" == status){
        //TODO:success action
        //mountDevice(uDiskPath);
        round->setPersent(100);
        playFinishGif();
        mountDevice(uDiskPath);
        qInfo()<<"status"<<status;
    }else if("unmount_error"==status){
            playLoadingGif();
            qInfo()<<"status"<<status;
    }else if("make_error"){
        playErrorGif();
        qInfo()<<"status"<<status;
    }
          //  playErrorGif();
    emit makeFinish();
}
bool Page2::mountDevice(QString target){

//    QProcess sync;
//    sync.start("sync");
//    sync.waitForStarted();
//    sync.waitForFinished();

    QProcess mount;
    qInfo()<<"start mounting disk:"<<target+"1";
    mount.start("udisksctl",QStringList{"mount","-b",target+"1"});
    if(!mount.waitForStarted()){
        qWarning()<<"count process start failed";
        return false;
    }
    if(!mount.waitForFinished()){
        qWarning()<<"装载失败";
        return false;
    }
    if(QProcess::NormalExit == mount.exitCode()){
        qInfo()<<"Mount success!";
        return true;
    }
    qWarning()<<"An unknown error occurred! Mount process exit code:"<<mount.exitCode();
    return false;
}

qint64 Page2::getFileSize(QString filePath)
{
    QFileInfo info(filePath);
    return info.size()/1048576;
}

void Page2::finishEvent()
{
    //mount disk at end of production
//    QProcess m_unmount;
//    QStringList m_unmount_arg;
//    m_unmount_arg <<"mount"<<"-b"<<uDiskPath;
//    m_unmount.start("udisksctl",m_unmount_arg);
//    if(m_unmount.waitForStarted()){
//        m_unmount.waitForFinished();
//    }else{
//        qDebug()<<"#udisksctl# Warning:mount failed! mount path :"<<uDiskPath;
//    }
    diskRefreshDelay = new QTimer;
    connect(diskRefreshDelay,&QTimer::timeout,[=]{
        diskRefreshDelay->stop();
        if(isMakingSuccess())
        {
            playFinishGif();
        }else
        {
            playErrorGif();
        }
        emit makeFinish();

    });
    diskRefreshDelay->start(1000);
}
bool Page2::isMakingSuccess()
{
    QList<QStorageInfo> diskList = QStorageInfo::mountedVolumes(); //mounted volumes
    for(QStorageInfo& disk : diskList)
    {
        QString diskPath = disk.device();
        diskPath = diskPath.mid(0,8);
        if(uDiskPath == diskPath)
        {
            return true;
        }
    }
    return false;
}

void Page2::movieRefresh()
{
    lableMovie->clear();
    switch(movieStatus)
    {
    case 0:
        playLoadingGif();
        break;
    case 1:
        playFinishGif();
        break;
    case 2:
        playErrorGif();
        break;
    }
}
void Page2::setThemeStyleLight()
{
    themeStatus = LIGHTTHEME;
    theme::baseColorFront=QColor(70,159,255);
    theme::backcolcr = QColor(250,250,250);
    theme::baseColorAfter=QColor(227,236,248);
    movieRefresh();
}

void Page2::setThemeStyleDark()
{
    themeStatus = DARKTHEME;
    theme::backcolcr=QColor(18,18,18);
    theme::baseColorFront=QColor(111,145,255);
    theme::baseColorAfter=QColor(43,44,46);
    movieRefresh();
}
void Page2::setIconchange(){
    if(lableText->text()==tr("Creation Failed")){
    lableMovie->setPixmap(QIcon::fromTheme("dialog-error").pixmap(96,96));
    }
    if(lableText->text()==tr("Finish")){
    lableMovie->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(96,96));
    }
}
