#include "copyimage.h"
#include "ui_copyimage.h"
#include "src/po/translation.h"
#include "src/frame/logger.h"
#include "src/frame/configuration.h"
#include "src/model/logicmain.h"
#include "src/model/logiccopyimage.h"
#include "src/model/menufactory.h"
#include "src/data/datacdrom.h"
#include "src/view/execdialog.h"

#include <QFileDialog>
#include <QFileSystemWatcher>
#include <QDebug>

CopyImage *CopyImage::m_oInstance = nullptr;
QMutex    CopyImage::m_oMutex;

CopyImage::CopyImage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CopyImage)
{
    QFont f;
    ui->setupUi(this);
    f = ui->title->font();
    f.setPixelSize(24);
    // f.setWeight(100);
    ui->title->setFont(f);
    ui->title->setFocusPolicy(Qt::NoFocus);
    ui->title->setText(_("CopyImage"));

    m_oDes.clear();
    m_oSrc.clear();

    f = ui->labelISOTitle->font();
    f.setPixelSize(14);
    ui->labelISOTip->setFont(f);
    ui->labelBurnerTip->setFont(f);
    ui->comboBoxBurner->setFont(f);
    //ui->comboBoxBurner->setModel(m_oListWidgetBurner->model());
    //ui->comboBoxBurner->setView(m_oListWidgetBurner);
    ui->comboBoxISO->setFont(f);
    //ui->comboBoxISO->setModel(m_oListWidget->model());
    //ui->comboBoxISO->setView(m_oListWidget);
    ui->btnBurnerSetting->setFont(f);
    ui->btnBurnerSetting->setText(_("Browse"));
    f.setWeight(60);
    ui->labelISOTitle->setFont(f);
    ui->labelISOTitle->setText(_("Please select disk which to be got or copied:"));
    ui->labelBurnerTitle->setFont(f);
    ui->labelBurnerTitle->setText(_("Please browse a valid path or empty disk:"));

    m_oShowISO = new QWidget(ui->isoWidget);
    m_oShowISO->setMinimumSize(ui->isoWidget->size());
    m_oShowISO->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    m_oIcon = new QLabel(m_oShowISO);
    m_oIcon->setFixedSize(25, 25);
    m_oDisplay = new QLabel(m_oShowISO);
    m_oDisplay->setFixedHeight(30);
    //m_oDisplay->setFixedWidth(ui->comboBoxISO->width() - 15);
    f = m_oDisplay->font();
    f.setPixelSize(14);
    m_oDisplay->setFont(f);
    QHBoxLayout *showISOLay = new QHBoxLayout(m_oShowISO);
    showISOLay->setMargin(0);
    showISOLay->addWidget(m_oIcon);
    //showISOLay->addSpacing(5);
    showISOLay->addWidget(m_oDisplay);
    showISOLay->addStretch(15);
    m_oShowISO->setFocusPolicy(Qt::NoFocus);
    m_oShowISO->setAttribute(Qt::WA_TransparentForMouseEvents, true);

    m_oShowBurner = new QWidget(ui->burnerWidget);
    m_oIconBurner = new QLabel(m_oShowBurner);
    m_oIconBurner->setFixedSize(25, 25);
    m_oDisplayBurner = new QLabel(m_oShowBurner);
    m_oDisplayBurner->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    m_oDisplayBurner->setFont(f);
    QHBoxLayout *showBurnerLay = new QHBoxLayout(m_oShowBurner);
    showBurnerLay->setMargin(0);
    showBurnerLay->addWidget(m_oIconBurner);
    showBurnerLay->addWidget(m_oDisplayBurner);
    showBurnerLay->addStretch(15);
    m_oShowBurner->setFocusPolicy(Qt::NoFocus);
    m_oShowBurner->setAttribute(Qt::WA_TransparentForMouseEvents, true);

    connect(COPY_IMGAE, SIGNAL(destination(void*)), this, SLOT(slotsDestination(void*)));
    connect(COPY_IMGAE, SIGNAL(destination(int)), this, SLOT(slotsDestination(int)));
    connect(ui->comboBoxBurner, SIGNAL(currentIndexChanged(int)), COPY_IMGAE, SLOT(slotsDestinationChange(int)));
    connect(ui->comboBoxBurner, SIGNAL(currentIndexChanged(int)), this, SLOT(slotsDestinationChange(int)));
    connect(COPY_IMGAE, SIGNAL(source(void*)), this, SLOT(slotsSource(void*)));
    connect(COPY_IMGAE, SIGNAL(source(int)), this, SLOT(slotsSource(int)));
    connect(ui->comboBoxISO, SIGNAL(currentIndexChanged(int)), COPY_IMGAE, SLOT(slotsSourceChange(int)));
    //connect(this, SIGNAL(busness(int)), MAIN, SLOT(slotsSetBusness(int)));
    connect(ui->btnBurnerSetting, SIGNAL(clicked(bool)), this, SLOT(slotsButtonClick()));
    //ui->labelISOTip->hide();

    ui->labelLogoISO->hide();
    ui->labelLogoBurner->hide();
}

CopyImage *CopyImage::instance()
{
    if (nullptr == m_oInstance)
    {
        QMutexLocker locker(&m_oMutex);
        if (nullptr == m_oInstance)
        {
            m_oInstance = new CopyImage();
        }
    }
    return m_oInstance;
}

void CopyImage::check()
{
    if (ui->comboBoxISO->currentIndex() < 0 ||
            ui->comboBoxBurner->currentIndex() < 0)
    {
        busness(false);
        if (ui->comboBoxBurner->currentIndex() > 0){
            ui->btnBurnerSetting->setEnabled(false);
        }
        else
            ui->btnBurnerSetting->setEnabled(true);
        return;
    }
    if (COPY_IMGAE->capacity())
    {
        busness(true);
        ui->btnBurnerSetting->setEnabled(true);
        if (ui->comboBoxBurner->currentIndex() == 0)
        {
            busness(LogicMain::GetISO);
        }
        else
        {
            busness(LogicMain::CopyData);
        }
        return;
    }
    busness(false);
    if (ui->comboBoxBurner->currentIndex() > 0)
        ui->btnBurnerSetting->setEnabled(false);
    else
        ui->btnBurnerSetting->setEnabled(true);
    if (ui->comboBoxBurner->currentIndex() == 0)
        busness(LogicMain::GetISO);
    else
        busness(LogicMain::CopyData);
}

void CopyImage::slotsDestination(void *d)
{
    DataCDROM *cdrom;
    cdrom = static_cast<DataCDROM *>(d);
    int index = m_oDes.indexOf(d);
    QString newDisplay = cdrom->mDisplay();
    if((-1 != index)){														//当设备容量更新时，更新复选框内的文字信息
        if(newDisplay != ui->comboBoxBurner->itemText(index))
            ui->comboBoxBurner->setItemText(index, newDisplay);
        return;
    }

    m_oDes << d;
    ui->comboBoxBurner->addItem(cdrom->mediumIcon(), cdrom->mDisplay());
    //ui->comboBoxBurner->addItem(cdrom->mediumIcon(), cdrom->mDisplay());
    check();
}

void CopyImage::slotsDestination(int idx)
{
    ui->comboBoxBurner->removeItem(idx);
    m_oDes.takeAt(idx);
    check();
}

void CopyImage::slotsSource(void *d)
{
    DataCDROM *cdrom;
    cdrom = static_cast<DataCDROM *>(d);
    ui->comboBoxISO->clear();
    ui->comboBoxISO->addItem(cdrom->mediumIcon(), cdrom->mDisplay());
    //ui->comboBoxISO->addItem(cdrom->mDisplay());
    m_oSrc << d;
    check();
}

void CopyImage::slotsSource(int idx)
{
    ui->comboBoxISO->removeItem(idx);
    m_oSrc.takeAt(idx);
    check();
}

void CopyImage::slotsButtonClick()
{
    QString path;
    QFileInfo f;

    if (ui->comboBoxBurner->currentIndex() > 0)
    {
        MENU->burnSetting(true);
        return;
    }

    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::DirectoryOnly);
    fd.setSidebarUrls(list + mntUrlList);
    if (fd.exec() != QDialog::Accepted) return;
    path = fd.selectedFiles().at(0);

    if (path.isEmpty()) return;
    f.setFile(path);
    if (!(f.permissions() & QFileDevice::WriteUser))
    {
        EXEC->error(_("Browse ISO Path"), _("Path %1 owner have no write permission.").arg(path));
        return;
    }
    path.append("/");
    COPY_IMGAE->updateISOPath(path);
    ui->comboBoxBurner->setItemText(0, path);
    update();
}

void CopyImage::slotsDestinationChange(int idx)
{
    // DataCDROM *cdrom;
    // QIcon icon;

    if (idx < 0) return;

    // cdrom = static_cast<DataCDROM *>(m_oDes.at(idx));

    // icon = cdrom->icon();
    // m_oIcon->setPixmap(icon.pixmap(m_oIcon->size()));
    if (idx > 0)
    {
        ui->btnBurnerSetting->setText(_("Setting"));
        busness(LogicMain::CopyData);
    }
    else
    {
        ui->btnBurnerSetting->setText(_("Browse"));
        busness(LogicMain::GetISO);
    }
    check();
}

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