#include "diskcheck.h"
#include "ui_diskcheck.h"
#include "src/data/datacdrom.h"
#include "src/model/logicmain.h"
#include "src/po/translation.h"
#include "src/process/processmd5sum.h"

#include <QFileInfo>
#include <QFileDialog>
#include <QFileSystemWatcher>

DiskCheck::DiskCheck(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DiskCheck)
{
    QFont f;
    ui->setupUi(this);

    m_oCDROMS.clear();
    m_oCheckFiles.clear();

    f = ui->title->font();
    f.setPixelSize(16);
    f.setBold(true);
    ui->title->setFont(f);

    f = ui->diskTitle->font();
    f.setPixelSize(14);
    //f.setWeight(60);
    ui->diskTitle->setFont(f);
    ui->fileTitle->setFont(f);
    f = ui->lineEdit->font();
    f.setPixelSize(14);
    ui->lineEdit->setFont(f);
    ui->comboBox->setFont(f);
    ui->pushButton->setFont(f);
    ui->lineEdit->setReadOnly(true);

    ui->title->setText(_("Disk Check"));
    ui->diskTitle->setText(_("Select a disc"));
    ui->fileTitle->setText(_("Check the disc using the MD5 file"));
    ui->pushButton->setText(_("Browse"));
    ui->pushButton->setEnabled(false);

    connect(MAIN, SIGNAL(appendableMedium(void*)), this, SLOT(slotsAddMedium(void*)));
    connect(MAIN, SIGNAL(finishedMedium(void*)), this, SLOT(slotsAddMedium(void*)));
    connect(MAIN, SIGNAL(noMedium(void*)), this, SLOT(slotsRemoveMedium(void*)));
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(slotsChangeMedium(int)));
    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(slotsBrowseFile()));
}

void DiskCheck::accept()
{
    int idx;
    ProcessMd5sum *md5Check;

    idx = ui->comboBox->currentIndex();
    if (idx < 0) return;

    md5Check = new ProcessMd5sum(m_oCDROMS.at(idx), m_oCheckFiles.at(idx), this);
    md5Check->exec();
    delete md5Check;
}

bool DiskCheck::check()
{
    if (ui->lineEdit->text().isEmpty()) return false;
    return true;
}

void DiskCheck::slotsAddMedium(void *c)
{
    int idx;
    DataCDROM *cdrom;
    QFileInfo f;
    QFileInfo f_data; //数据校验文件

    idx = m_oCDROMS.indexOf(c);
    if (-1 == idx)
    {
        m_oCDROMS << c;
        cdrom = static_cast<DataCDROM *>(c);
        f.setFile(cdrom->mediumMountPoint().append("/").append("md5sum.txt"));
        f_data.setFile(cdrom->mediumMountPoint().append("/").append(".md5sum.txt"));

        if (f.exists()) {
            m_oCheckFiles << f.absoluteFilePath();
        } else if (f_data.exists()) {
            m_oCheckFiles << f_data.absoluteFilePath();
        } else
            m_oCheckFiles << QString();

        ui->comboBox->addItem(cdrom->mediumIcon(), cdrom->mDisplay());
        ui->comboBox->setCurrentIndex(m_oCDROMS.indexOf(c));
        change(check());
    }
    if (m_oCDROMS.size() > 0) ui->pushButton->setEnabled(true);
}

void DiskCheck::slotsRemoveMedium(void *c)
{
    int idx;

    idx = m_oCDROMS.indexOf(c);

    if (-1 != idx)
    {
        m_oCDROMS.takeAt(idx);
        m_oCheckFiles.takeAt(idx);
        ui->comboBox->removeItem(idx);
        change(check());
    }

    if (m_oCDROMS.size() <= 0) {
        ui->pushButton->setEnabled(false);
        ui->lineEdit->clear();
    }
}

void DiskCheck::slotsChangeMedium(int idx)
{
    if (-1 == idx) return;
    if (idx >= m_oCDROMS.size()) return;
    ui->lineEdit->setText(m_oCheckFiles.at(idx));
    ui->lineEdit->setCursorPosition(0);
    ui->lineEdit->setToolTip(m_oCheckFiles.at(idx));
    change((check()));
}

void DiskCheck::slotsBrowseFile()
{
    QString file;
    QFileDialog fd;
    QList<QUrl> list = fd.sidebarUrls();
    int sidebarNum = 8;//最大添加U盘数，可以自己定义
    QString home = QDir::homePath().section("/", -1, -1);
    QString mnt = "/media/" + home + "/";
    QDir mntDir(mnt);
    mntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList filist = mntDir.entryInfoList();
    QList<QUrl> mntUrlList;
    for (int i = 0; i < sidebarNum && i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);

        if (fi.fileName() == "2691-6AB8") /* 990 9a0 */
                 continue;

        mntUrlList << QUrl("file://" + fi.filePath());
    }

    QFileSystemWatcher fsw(&fd);
    fsw.addPath("/media/" + home + "/");
    connect(&fsw, &QFileSystemWatcher::directoryChanged, &fd,
            [=, &sidebarNum, &mntUrlList, &list, &fd](const QString path) {
        QDir wmntDir(path);
        wmntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList wfilist = wmntDir.entryInfoList();
        mntUrlList.clear();
        for (int i = 0; i < sidebarNum && i < wfilist.size(); ++i) {
            QFileInfo fi = wfilist.at(i);

            if (fi.fileName() == "2691-6AB8") /* 990 9a0 */
                     continue;

            mntUrlList << QUrl("file://" + fi.filePath());
        }
        fd.setSidebarUrls(list + mntUrlList);
        fd.update();
    });

    connect(&fd, &QFileDialog::finished, &fd, [=, &list, &fd]() {
        fd.setSidebarUrls(list);
    });


    fd.setFileMode(QFileDialog::ExistingFile);
    fd.setSidebarUrls(list + mntUrlList);
    if (fd.exec() != QDialog::Accepted) return;
    file = fd.selectedFiles().at(0);

    //file = QFileDialog::getOpenFileName(nullptr, _("Burner") + " - " + _("Browse"));
    ui->lineEdit->setText(file);
    ui->lineEdit->setCursorPosition(0);
    ui->lineEdit->setToolTip(file);
    m_oCheckFiles.replace(ui->comboBox->currentIndex(), file);
    change(check());
}

DiskCheck::~DiskCheck()
{
    delete ui;
}
