/*
 * Copyright (C) 2002  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 Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "page1.h"
#include "include/xatom-helper.h"


Page1::Page1()
{
    initControlQss();//初始化样式
    getStorageInfo();//获取磁盘信息
}
void Page1::initControlQss()
{
    edit = new line;
    edit->installEventFilter(this);
   // topwidget1 = new QWidget(this);
   // topwidget1->setFixedSize(450,300);
   // topwidget1->hide();
    topwidget=new QWidget(this);
    fram=new QFrame;
    fram->setFrameShape(QFrame::NoFrame);
    //fram->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
   // top=new topborder(this);
  //  top->hide();
    fram->setGeometry(40,95,500,400);
    fram->hide();
    topwidget->setFixedSize(450,320);
    tabUdisk1 = new QLabel(fram);
    tabUdisk1->setFixedSize(127,127);
    urlIso=new QLabel(topwidget);
    urlIso1=new QLabel(fram);
    QPixmap pix(":/data/button lightmode inactive.png");
    urlIso1->setText(tr("Drag and drop the image file here"));
    tabUdisk1->setPixmap(pix);
    urlIso->setWordWrap(true);
    urlIso->setEnabled(false);
    urlIso->setText(tr("Click or drag to add a mirror file"));
    urlIso->setAlignment(Qt::AlignHCenter);
    urlIso1->setAlignment(Qt::AlignHCenter);
    urlIso1->setWordWrap(true);
    comboUdisk = new QComboBox(this);
    comboUdisk->setFixedSize(400,40);
    comboUdisk->setEnabled(false);
    QWidget *btnwidget = new QWidget(this);
    findIso=new QPushButton(btnwidget);
    findIso->setStyleSheet("QPushButton{border-image:url(:/data/button lightmode normal.png);}"
                           "QPushButton:hover{border-image:url(:/data/button lightmode hover.png);}"
                           "QPushButton:clicked{border-image:url(:/data/button lightmode click.png);}");
    findIso->setFixedSize(127,127);
    creatStart=new QPushButton(btnwidget);
    creatStart->setText(tr("Start"));
    creatStart->setEnabled(false);
    connect(findIso,&QPushButton::clicked,this,[=]{
        isoPath = QFileDialog::getOpenFileName(0,tr("choose iso file"),QDir::homePath(),"ISO(*.iso)");
        dealSelectedFile(isoPath);
    });
    connect(edit,&QLineEdit::textChanged,this,&Page1::ifStartBtnChange);
    connect(creatStart,&QPushButton::clicked,[=]{
       emit starmake(isoPath,diskInfos[comboUdisk->currentIndex()]->devicePath);

        QDBusMessage m = QDBusMessage::createMethodCall("com.kylinusbcreator.systemdbus","/",
                                                        "com.kylinusbcreator.interface","MakeStart");
        m<<isoPath;
        QString usb=diskInfos[comboUdisk->currentIndex()]->devicePath;
        //m<<diskInfos[comboUdisk->currentIndex()]->devicePath;
        m<<usb;
        QDBusConnection::systemBus().call(m);
    });
    QHBoxLayout *hlay=new QHBoxLayout(this);
    btnwidget->setLayout(hlay);
    hlay->addStretch(100);
    hlay->addWidget(creatStart);
    hlay->addStretch(100);
    QVBoxLayout *vlay1 = new QVBoxLayout(this);
    QVBoxLayout *vlay2 = new QVBoxLayout(this);
//    if(comboUdisk->currentText()!=tr("No USB drive available")){
//        qInfo()<<"wenbenshuchu";
//        edit->installEventFilter(this);
//    }
    topwidget->setLayout(vlay1);
    fram->setLayout(vlay2);
    vlay1->addWidget(findIso,0,Qt::AlignCenter);
    vlay1->addWidget(urlIso,0,Qt::AlignCenter);
    vlay1->addSpacing(70);
    vlay2->addWidget(tabUdisk1,0,Qt::AlignCenter);
    vlay2->addSpacing(150);
    vlay2->addWidget(urlIso1,0,Qt::AlignCenter);
    vlay2->addSpacing(70);
    QVBoxLayout *vlay =new QVBoxLayout(this);
    vlay->addSpacing(100);
   // vlay->addWidget(topwidget1,0,Qt::AlignCenter);
    vlay->addWidget(fram,0,Qt::AlignCenter);
    vlay->addWidget(topwidget,0,Qt::AlignCenter);
    vlay->addSpacing(50);
    vlay->addWidget(comboUdisk,0,Qt::AlignCenter);
    vlay->addSpacing(30);
    vlay->addWidget(btnwidget);
    vlay->addSpacing(30);
    udiskPlugWatcherInit(); //监控U盘插拔
}
//{
//    tabIso=new QLabel;
//    tabUdisk=new QLabel;
//    tabIso->setText(tr("Choose iso file"));
//    tabUdisk->setText(tr("Select USB drive"));
//    tabIso->setFixedHeight(30);
//    tabUdisk->setFixedHeight(30);
//    tabIso->setObjectName("tabLable");
//    tabUdisk->setObjectName("tabLable");
//    comboUdisk = new QComboBox();
//    warnningIcon=new QLabel;
//    warnningIcon->setStyleSheet("border-image:url(:/data/warning.png);border:0px;");
//    warnningIcon->setFixedSize(24,24);
//    warnningText=new QLabel;
//    urlIso=new QLineEdit;
//    urlIso->setEnabled(false);
//    urlIso->setFixedHeight(40);
//    findIso=new QPushButton();
//    findIso->setText(tr("Open"));
//    findIso->setFixedSize(80,40);
//    connect(findIso,&QPushButton::clicked,this,[=]{
//            isoPath = QFileDialog::getOpenFileName(0,tr("choose iso file"),QDir::homePath(),"ISO(*.iso)");
//            dealSelectedFile(isoPath);
//        });
//    connect(urlIso,&QLineEdit::textChanged,this,&Page1::ifStartBtnChange);
//    creatStart=new QPushButton(this);
//    creatStart->setFixedSize(200,30);
//    creatStart->setText(tr("Start"));
//    creatStart->setEnabled(false);
//    connect(creatStart,&QPushButton::clicked,[=]{
//        QDBusMessage m = QDBusMessage::createMethodCall("com.kylinusbcreator.systemdbus","/",
//                                                        "com.kylinusbcreator.interface","MakeStart");
//        m<<isoPath;
//        m<<diskInfos[comboUdisk->currentIndex()]->devicePath;
//        QDBusConnection::systemBus().call(m);
//    });

//    QHBoxLayout *hl1=new QHBoxLayout;
//    hl1->setMargin(0);
//    hl1->setSpacing(0);
//    hl1->addWidget(urlIso,9);
//    hl1->addSpacing(10);
//    hl1->addWidget(findIso,1);
//    QHBoxLayout *hl2=new QHBoxLayout;
//    hl2->setMargin(0);
//    hl2->setSpacing(0);
//    hl2->addWidget(warnningIcon,1);
//    hl2->addSpacing(5);
//    hl2->addWidget(warnningText,9);
//    QHBoxLayout *hl3=new QHBoxLayout;
//    hl3->setMargin(0);
//    hl3->setSpacing(0);
//    hl3->addStretch(9);
//    hl3->addWidget(creatStart);
//    hl3->addStretch(9);
//    QVBoxLayout *vl0=new QVBoxLayout;
//    vl0->setMargin(0);
//    vl0->setSpacing(0);
//    vl0->addStretch(4);
//    vl0->addWidget(tabIso);
//    vl0->addSpacing(10);
//    vl0->addLayout(hl1);
//    vl0->addStretch(3);
//    vl0->addWidget(tabUdisk);
//    vl0->addSpacing(10);
//    vl0->addWidget(comboUdisk);
//    vl0->addSpacing(10);
//    vl0->addLayout(hl2);
//    vl0->addStretch(8);
//    vl0->addLayout(hl3);
//    vl0->addStretch(2);
//    QHBoxLayout *vl00=new QHBoxLayout;
//    vl00->addStretch(3);
//    vl00->addLayout(vl0,8);
//    vl00->addStretch(3);
//    this->setLayout(vl00);
//    warnningText->setText(tr("USB drive will be formatted,please backup your files!"));
//    udiskPlugWatcherInit(); //监控U盘插拔
//}

void Page1::udiskPlugWatcherInit()
{
    comboUdisk->setEnabled(true);
    diskRefreshDelay = new QTimer;
    connect(diskRefreshDelay,&QTimer::timeout,this,&Page1::getStorageInfo);
    udiskplugwatcher = new QFileSystemWatcher(this);
    udiskplugwatcher->addPath("/dev");
    connect(udiskplugwatcher,&QFileSystemWatcher::directoryChanged,this,&Page1::refreshDiskList);
}

void Page1::refreshDiskList()
{
    if(diskRefreshDelay->isActive())
    {
        return;
    }
    comboUdisk->clear();
    diskRefreshDelay->start(1000);
}

bool Page1::isCapicityAvailable(QString str)
{
    if(str[str.length()-1] == 'G')
    {
       str.chop(1);//去掉最后一位
       if(str.toFloat() < 65 && str.toFloat() > 4)
       {
           return true;
       }
    }
    return false;
}

bool Page1::checkISO(const QString fileName){
    // Check if there's an MBR signature
    // MBR signature will be in last two bytes of the boot record
    QByteArray mbr;
    QFile mbrTest(fileName);
    mbrTest.open(QIODevice::ReadOnly);
    mbrTest.seek(510);
    mbr = mbrTest.read(2);
    mbrTest.close();
    if (mbr.toHex() != "55aa"){ //MBR signature "55aa"
        qDebug()<<"wrong iso,filename = "<<fileName<<"MBR signature = "<<mbr.toHex();
        return false;
    }
    return true;
}

void Page1::getUdiskPathAndCap()
{
    diskInfos.clear();
    QProcess lsblk;
    lsblk.start("lsblk -J");
    lsblk.waitForFinished();

    QProcess lsblk2;
    lsblk2.start("lsblk -JS");
    lsblk2.waitForFinished();
    QJsonArray arr1 = QStringToJsonArray(QString::fromLocal8Bit(lsblk.readAllStandardOutput()));  //获取json类型的shell执行结果
    QJsonArray arr2 = QStringToJsonArray(QString::fromLocal8Bit(lsblk2.readAllStandardOutput()));
    foreach (const QJsonValue& value, arr1) {
        QJsonObject jsonObj1 = value.toObject();
        foreach (const QJsonValue& value, arr2) {
            QJsonObject jsonObj2 = value.toObject();
            if(jsonObj1["name"] == jsonObj2["name"] && jsonObj2["tran"] == "usb" && jsonObj2["type"] == "disk"){
                AvailableDiskInfo *tmp = new AvailableDiskInfo("/dev/" + jsonObj1["name"].toString(),jsonObj2["model"].toString(),jsonObj1["size"].toString());
                diskInfos.append(tmp);
            }
        }
    }
}

QJsonArray  Page1::QStringToJsonArray(const QString jsonString){
    QJsonParseError err;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toLocal8Bit().data(),&err);
    if(jsonDocument.isNull())
    {
        qWarning()<< "JsonDocument is NULL.Origin data is:"<< jsonString.toLocal8Bit().data();
    }
    if(err.error != QJsonParseError::NoError){
        qWarning()<<"Parase json"<<jsonString<<" error:"<<err.error;
    }
    QJsonObject obj = jsonDocument.object();
    return obj["blockdevices"].toArray();
}
void Page1::getUdiskName()
{
    QList<QStorageInfo> storageInfo = QStorageInfo::mountedVolumes();
    foreach(AvailableDiskInfo* tmp,diskInfos)  //lsblk命令拿到的可用U盘信息
    {
        foreach(QStorageInfo disk,storageInfo)
        {
            if((disk.device().length() == 8 && tmp->devicePath == disk.device()))
            {
                tmp->displayName = disk.displayName();
                float cap = disk.bytesTotal();
                tmp->diskCapicity = QString::number(cap/1000000000,'f',1) + 'G';
                continue;
            }
            if(tmp->devicePath + '1' == disk.device())  //使用第一个分区的名字做展示名
            {
                tmp->displayName = disk.displayName();
                tmp->diskCapicity = disk.bytesTotal();
                float cap = disk.bytesTotal();
                tmp->diskCapicity = QString::number(cap / 1000000000,'f',1) + 'G';
                continue;
            }
        }
    }
}

void Page1::getStorageInfo()
{
    diskRefreshDelay->stop();//U盘动态刷新相关
    getUdiskPathAndCap();

    foreach(AvailableDiskInfo *diskInfo,diskInfos)
    {
        //过长的名称做去尾加省略号
        if(diskInfo->displayName.length() > UDISK_NAME_MAX_LENGTH)
        {
            diskInfo->displayName = diskInfo->displayName.mid(0,UDISK_NAME_MAX_LENGTH - 1) + "…";
        }
        QString info = diskInfo->displayName+" ("+diskInfo->devicePath + ") " + diskInfo->diskCapicity;

        comboUdisk->addItem(info,diskInfo->devicePath);
        comboUdisk->setEnabled(true);
    }
    if(comboUdisk->count()!=1){
        comboUdisk->setCurrentIndex(-1);
        comboUdisk->setLineEdit(edit);
        edit->setText(tr("select USB flash drive"));
        edit->setReadOnly(true);
    }
//    comboUdisk->setCurrentIndex(-1);
//    comboUdisk->setLineEdit(edit);
//    edit->setText(tr("select USB flash drive"));
//    edit->setReadOnly(true);
    if(0==comboUdisk->count())
    {
        comboUdisk->addItem(tr("No USB drive available"));
        comboUdisk->setEnabled(false);
        creatStart->setEnabled(false);
    }
    emit diskLabelRefresh();

    ifStartBtnChange();
}

void Page1::creatStartSlots()
{
    creatStart->setEnabled(false);
}

bool Page1::ifStartBtnChange()
{
    if(comboUdisk->currentText() != tr("No USB drive available")&&edit->text()!=tr("select USB flash drive") && urlIso->text()==isoPath)
    {
        creatStart->setEnabled(true);
        return true;
    }else{
        creatStart->setEnabled(false);
        return false;
    }
}

void Page1::dealDialogCancel()
{
    ifStartBtnChange();
}

void Page1::dealComboBoxChangeButton()
{
    ifStartBtnChange();
}

void Page1::dealAuthDialogClose()
{
    creatStart->setEnabled(true);
}

void Page1::setThemeStyleLight()
{
    themeStatus = LIGHTTHEME;
    QPixmap pix(":/data/button lightmode inactive.png");
    tabUdisk1->setPixmap(pix);
    findIso->setStyleSheet("QPushButton{border-image:url(:/data/button lightmode normal.png);}"
                           "QPushButton:hover{border-image:url(:/data/button lightmode hover.png);}"
                           "QPushButton:clicked{border-image:url(:/data/button lightmode click.png);}");
  //  QPixmap pix(":/data/Placeholder lighter.png");
  //  tabUdisk->setPixmap(pix);

    ifStartBtnChange();
}

void Page1::setThemeStyleDark()
{
    themeStatus = DARKTHEME;
    QPixmap pix(":/data/button darkmode inactive.png");
    tabUdisk1->setPixmap(pix);
    findIso->setStyleSheet("QPushButton{border-image:url(:/data/button darkmode normal.png);}"
                           "QPushButton:hover{border-image:url(:/data/button darkmode hover.png);}"
                           "QPushButton:clicked{border-image:url(:/data/button darkmode click.png);}");
 //   QPixmap pix(":/data/Placeholder dark.png");
  //  tabUdisk->setPixmap(pix);
    ifStartBtnChange();
}

QString Page1::getDevPath(){
    return diskInfos[comboUdisk->currentIndex()]->devicePath;
}

void Page1::dealSelectedFile(QString isoPath){
    if(isoPath.isEmpty()){
        return ;
    }
    if(comboUdisk->currentText() != tr("No USB drive available") && edit->text() != tr("select USB flash drive")){
        creatStart->setEnabled(true);
    }
    if(!checkISO(isoPath)){
        QMessageBox::StandardButton result =  QMessageBox::warning(this,tr("Warning"),tr("MBR signature not detected,continue anyway?"),
                             QMessageBox::Yes | QMessageBox::No);
        switch (result)
        {
        case QMessageBox::Yes:
            if(comboUdisk->currentText() != tr("No USB drive available") && edit->text() != tr("select USB flash drive")){
                creatStart->setEnabled(true);
            }
            break;
        case QMessageBox::No:
            isoPath.clear();
            break;
        }
    }
    //以右键点击镜像打开方式u盘启动器点击制作会提示没有文件路径会发现是因为isopath是成员变量开启，需要进行传值。才可以制作。
    this->isoPath = isoPath;
    urlIso->setToolTip("");
  //  if(isoPath.length() > 50){
      urlIso->setToolTip(isoPath);
   //     urlIso->setText(isoPath.mid(0,49) + "...");
  //  }else{
        urlIso->setText(isoPath);
        urlIso1->setText(isoPath);
        urlIso1->setToolTip(isoPath);
//    }
    return ;
}
void Page1::dragEnterEvent(QDragEnterEvent *event){
    auto urls = event->mimeData()->urls();
    if(urls.length() != 1){
        return ;
    }
    QString filePath = urls.at(0).toLocalFile();
    if("iso" != QFileInfo(filePath).suffix().toLower()){
        return ;
    }
    if(event->mimeData()->hasFormat("text/uri-list")){
        qInfo()<<"437"<<filePath;
        fram->setFrameShape(QFrame::StyledPanel);
        fram->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
        fram->show();
      //  topwidget1->show();
        topwidget->hide();
//       top->show();
       event->acceptProposedAction();
    }
    return QWidget::dragEnterEvent(event);
}
void Page1::dragLeaveEvent(QDragLeaveEvent *event){
        findIso->show();
        topwidget->show();
        fram->hide();
    return QWidget::dragLeaveEvent(event);

}
void Page1::dropEvent(QDropEvent *event){
    auto urls = event->mimeData()->urls();
    if(urls.isEmpty())
        return ;
    for(auto url:urls){
        dealSelectedFile(url.toLocalFile());
        findIso->show();
        topwidget->show();
        fram->hide();
        ifStartBtnChange();
    }
    return ;
}
void Page1::settingStyle(){
    subject=new GsettingSubject;
    connect(subject,&GsettingSubject::blackStyle,this,[=]{
        this->setThemeStyleDark();
    });
    connect(subject,&GsettingSubject::whiteStyle,this,[=]{
       this->setThemeStyleLight();
    });
    subject->iniWidgetStyle();
}
bool Page1::eventFilter(QObject *watched, QEvent *event){
    if(watched==edit){
        if(event->type()==QEvent::MouseButtonPress){
            if(comboUdisk->currentText()!=tr("No USB drive available")){
                qInfo()<<"wenbenshuchu";
                comboUdisk->showPopup();
            }
        }
    }
    return QWidget::eventFilter(watched,event);
}
