#include "busnesssetting.h"
#include "ui_busnesssetting.h"
#include "src/data/datacdrom.h"
#include "src/po/translation.h"
#include "src/view/modaldialog.h"
#include "src/model/logicburnimage.h"
#include "src/model/logiccopyimage.h"
#include "src/model/logicmain.h"
#include "src/frame/signals.h"
#include "src/view/components/iconlabel.h"
#include "src/view/multiselectionfiledialog.h"

#include <QPalette>
#include <QDebug>
#include <QDir>
#include <QStorageInfo>
#include <QFileDialog>
#include <QMessageBox>
#include <QFont>
#include <ukuistylehelper/ukuistylehelper.h>

BusnessSetting::BusnessSetting(QWidget *parent) :
    QWidget(parent),
    m_bVerfication(false),
    m_bCreateISO(false),
    ui(new Ui::BusnessSetting)
{
    QFont f;
    ui->setupUi(this);

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

    f = ui->labelISOInfo->font();
    f.setPixelSize(14);
    f.setWeight(60);
    ui->labelISOInfo->setFont(f);
    ui->labelISOInfo->setText(_("ISO info"));
    ui->labelCopyright->setFont(f);
    ui->labelCopyright->setText(_("Copyright"));
    //ui->labelISOSetting->setFont(f);
    //ui->labelISOSetting->setText(_("After ISO:"));
    ui->labelPreparer->setFont(f);
    ui->labelPreparer->setText(_("Preparer"));
    ui->labelPublisher->setFont(f);
    ui->labelPublisher->setText(_("Publisher"));
    ui->labelVolumnID->setFont(f);
    ui->labelVolumnID->setText(_("VolumeID"));
    ui->labelTempPath->setFont(f);
    ui->labelTempPath->setText(_("Temporary path"));
    //ui->labelBurnerSetting->setFont(f);
    //ui->labelBurnerSetting->setText(_("After burned:"));
    ui->labelBurnSpeed->setFont(f);
    ui->labelBurnSpeed->setText(_("Burn Speed"));
    ui->labelBurnFormat->setFont(f);
    ui->labelBurnFormat->setText(_("Burn Format"));
    //f = ui->btnBrowse->font();
    f.setPixelSize(14);
    ui->lineEditCopyright->setFont(f);
    ui->lineEditPreparer->setFont(f);
    ui->lineEditPublisher->setFont(f);
    ui->lineEditTempPath->setFont(f);
    ui->lineEditVolumnID->setFont(f);
    ui->comboBoxBurnSpeed->setFont(f);
    ui->comboBoxBurnFormat->setFont(f);
    /*ui->btnBrowse->setFont(f);
    ui->btnBrowse->setText(_("Browse"));
    ui->checkBoxBunerClean->setFont(f);
    ui->checkBoxBunerClean->setText(_("Clean File(s)"));
    ui->checkBoxClean->setFont(f);
    ui->checkBoxClean->setText(_("Clean File(s)"));*/
    ui->checkBoxCloseSeeion->setFont(f);
    ui->checkBoxCloseSeeion->setText(_("Close session"));
    ui->checkBoxCreateISO->setFont(f);
    ui->checkBoxCreateISO->setText(_("Create ISO"));
    ui->checkBoxVerfication->setFont(f);
    ui->checkBoxVerfication->setText(_("Data Verfication"));
    /*ui->checkBoxOpen->setFont(f);
    ui->checkBoxOpen->setText(_("Open belong URL"));
    ui->checkBoxBunerClean->hide();*/


    m_oBrowsePath.clear();
    m_oCDROM = nullptr;
#if 0
    // 确定 按钮一直可用，可不用改操作
    //connect(ui->btnBrowse, SIGNAL(clicked(bool)), this, SLOT(slotsBrowse()));
    connect(ui->lineEditCopyright, SIGNAL(textEdited(QString)), this, SLOT(slotsChange()));
    connect(ui->lineEditPreparer, SIGNAL(textEdited(QString)), this, SLOT(slotsChange()));
    connect(ui->lineEditPublisher, SIGNAL(textEdited(QString)), this, SLOT(slotsChange()));
    connect(ui->lineEditVolumnID, SIGNAL(textEdited(QString)), this, SLOT(slotsChange()));
    connect(ui->lineEditTempPath, SIGNAL(editingFinished()), this, SLOT(slotsChange()));
    //connect(ui->checkBoxBunerClean, SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    //connect(ui->checkBoxClean, SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    connect(ui->checkBoxCloseSeeion, SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    connect(ui->checkBoxCreateISO, SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    connect(ui->checkBoxVerfication,SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    //connect(ui->checkBoxOpen, SIGNAL(stateChanged(int)), this, SLOT(slotsChange()));
    connect(ui->comboBoxBurnSpeed, SIGNAL(currentIndexChanged(int)), this, SLOT(slotsChange()));
    connect(ui->comboBoxBurnFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(slotsChange()));
#endif
    uiAdjust();
}


void BusnessSetting::load(void *d)
{
    //点击"设置"按钮后，为界面赋值
    DataCDROM *cdrom;
    m_oCDROM = d;

    cdrom = static_cast<DataCDROM *>(d);
    //if (cdrom) cdrom->use();
    cdrom->setting();
    //qDebug()<<"cdrom.m_oSetting.load()  speed(),burnFormat()";
    //qDebug()<<"cdrom->m_oSetting->m_SBurnFormat==["<<cdrom->getBurnFormat()<<"]";
    //ui->checkBoxBunerClean->setEnabled(true);
    //ui->checkBoxClean->setEnabled(true);
    ui->checkBoxCloseSeeion->setEnabled(false);
    ui->checkBoxCreateISO->setEnabled(true);
    ui->checkBoxVerfication->setEnabled(true);
    //ui->checkBoxOpen->setEnabled(true);
    ui->lineEditCopyright->setReadOnly(false);
    ui->lineEditPreparer->setReadOnly(false);
    ui->lineEditPublisher->setReadOnly(false);
    ui->lineEditVolumnID->setReadOnly(false);

    if (cdrom->isCDROM() && cdrom->mediumStatus() != DataMedium::MEDIUM_EMPTY)
    {
        ui->lineEditCopyright->setReadOnly(true);
        ui->lineEditPreparer->setReadOnly(true);
        ui->lineEditPublisher->setReadOnly(true);
        //ui->lineEditVolumnID->setReadOnly(true);
        ui->checkBoxCreateISO->setChecked(true);
        ui->checkBoxCreateISO->setEnabled(true);
    }
    else
    {
        ui->lineEditCopyright->setReadOnly(false);
        ui->lineEditPreparer->setReadOnly(false);
        ui->lineEditPublisher->setReadOnly(false);
        //ui->lineEditVolumnID->setReadOnly(false);
        ui->checkBoxCreateISO->setChecked(true);
        ui->checkBoxCreateISO->setEnabled(true);
    }

    m_oSpeed = cdrom->mediumSpeed();
    m_oSpeeds.clear();
    while (m_oSpeed.size())
    {
        m_oSpeeds << m_oSpeed.takeFirst().toInt();
    }
    ui->comboBoxBurnSpeed->clear();
    for (int i = 0; i < m_oSpeeds.size(); ++i)
    {
        ui->comboBoxBurnSpeed->addItem(QString("%1x").arg(m_oSpeeds.at(i)));
    }
    if (0 == m_oSpeeds.size())
        ui->comboBoxBurnSpeed->setEnabled(false);
    else
        ui->comboBoxBurnSpeed->setEnabled(true);

    #if 1
    //使用UDF格式或ISO9660，默认ISO9660
    m_oBurnFormat.clear();
    ui->comboBoxBurnFormat->clear();
    m_oBurnFormat<< QString("ISO9660");
    if(cdrom->isEnableUDF())
    {  
        m_oBurnFormat<< QString("UDF");
    }
    for(int i=0; i<m_oBurnFormat.size(); ++i)
    {
        ui->comboBoxBurnFormat->addItem(QString("%1").arg(m_oBurnFormat.at(i)));
    }
    if (0 == m_oBurnFormat.size())
        ui->comboBoxBurnFormat->setEnabled(false);
    else
        ui->comboBoxBurnFormat->setEnabled(true);
    #endif


    m_oPreparer = cdrom->settingPreparer();
    m_oCopyright = cdrom->settingCopyright();
    m_oPublisher = cdrom->settingPublisher();
    m_oVolumnID = cdrom->settingVolumnID();
    ui->lineEditPreparer->setText(m_oPreparer);
    ui->lineEditCopyright->setText(m_oCopyright);
    ui->lineEditPublisher->setText(m_oPublisher);
    ui->lineEditVolumnID->setText(m_oVolumnID);

    //ui->checkBoxBunerClean->setChecked(m_bClean);
    //ui->checkBoxClean->setChecked(m_bClean);
    if (BURNIMAGE == sender() || cdrom->mediumType().contains("DVD+RW"))
    {
        m_bCloseSession = true;
    }
    else
    {
        m_bCloseSession = cdrom->settingCloseSession();
        qDebug()<<__LINE__<<__func__<<m_bCloseSession;
    }
    //ui->checkBoxCloseSeeion->setChecked(m_bCloseSession);

    m_bVerfication = cdrom->settingVerficationData();
    ui->checkBoxVerfication->setChecked(cdrom->settingVerficationData());

    if (BURNIMAGE == sender() || cdrom->mediumType().contains("DVD"))
    {
        ui->checkBoxCloseSeeion->setEnabled(false);
        ui->checkBoxCreateISO->setEnabled(true);
        ui->lineEditCopyright->setReadOnly(true);
        ui->lineEditPreparer->setReadOnly(true);
        ui->lineEditPublisher->setReadOnly(true);
        //ui->lineEditVolumnID->setReadOnly(true);
    }
    else
    {
        ui->checkBoxCloseSeeion->setEnabled(false);
    }
    if (BURNIMAGE == sender() || COPY_IMGAE == sender())
    {
        //ui->btnBrowse->setEnabled(false);
        ui->lineEditVolumnID->setReadOnly(true);
        ui->lineEditVolumnID->setText(_("KylinBurner"));
    }
    else
    {
        //ui->btnBrowse->setEnabled(true);
    }

    ui->checkBoxCreateISO->setChecked(m_bCreateISO);
    //ui->checkBoxOpen->setChecked(m_bOpen);
    setTemporaryPath(m_oTemporaryPth);

    if (cdrom->isCDROM())
    {
        ui->title->setText(_("BurnSetting"));
        title(_("BurnSetting"));
        //ui->widgetISOSetting->hide();
        //ui->widgetBurnSetting->show();
        //ui->widgetSpeed->show();
        ui->line->show();

        if (-1 != m_oSpeeds.indexOf(m_iSpeed))
        {
            //qDebug() <<"m_iSpeed==["<<m_iSpeed<<"]";
            ui->comboBoxBurnSpeed->setCurrentIndex(m_oSpeeds.indexOf(m_iSpeed));
        }

        if (-1 != m_oBurnFormat.indexOf(m_SBurnFormat))
        {
            //qDebug() <<"m_SBurnFormat==["<<m_SBurnFormat<<"]";
            ui->comboBoxBurnFormat->setCurrentIndex(m_oBurnFormat.indexOf(m_SBurnFormat));
        }

    }
    else
    {
        ui->title->setText(_("ISOSetting"));
        title(_("ISOSetting"));
        /*ui->widgetISOSetting->show();
        ui->widgetBurnSetting->hide();
        ui->widgetSpeed->hide();*/
        //ui->line->hide();
    }

    if (COPY_IMGAE == sender())
    {
        ui->lineEditCopyright->setReadOnly(true);
        ui->lineEditPreparer->setReadOnly(true);
        ui->lineEditPublisher->setReadOnly(true);
        ui->lineEditVolumnID->setReadOnly(true);
        //ui->checkBoxBunerClean->setEnabled(false);
        //ui->checkBoxClean->setEnabled(false);
        ui->checkBoxCloseSeeion->setEnabled(false);
        ui->checkBoxCreateISO->setEnabled(true);
        ui->checkBoxVerfication->setEnabled(false);
        //ui->checkBoxOpen->setEnabled(false);
    }
    //if (cdrom) cdrom->release();
    //qDebug()<<"BusnessSetting::load  end-----";
    ui->checkBoxCreateISO->setEnabled(true);

    //确定和取消按钮可用
    emit ensureBtnStateChanged(true);
    emit cancelBtnStateChanged(true);
}

void BusnessSetting::setVolumnID(QString s)
{
     m_oVolumnID = s;
     ui->lineEditVolumnID->setText(m_oVolumnID);
}

void BusnessSetting::setTemporaryPath(QString path)
{
    int u = -1;
    QDir dir(path);
    if (path.isEmpty() || !dir.exists())
        return;

//    int u = -1;
//    QDir dir(path);
//    QStorageInfo storage(path);
//    qreal size = storage.bytesAvailable();
//    QString name;

//    while (size > 1024.00)
//    {
//        ++u; size /= 1024.00;
//    }
//    name = QString("Usage: %1 Free Space: %2").arg(dir.dirName()).arg(size, 0, 'f', 1);
//    switch (u)
//    {
//    case 0:
//        name.append(_("KB"));
//        break;
//    case 1:
//        name.append(_("MB"));
//        break;
//    case 2:
//        name.append(_("GB"));
//        break;
//    case 3:
//        name.append(_("TB"));
//        break;
//    case 4:
//        name.append(_("PB"));
//        break;
//    default:
//        name.append(_("B"));
//        break;
//    }
    ui->lineEditTempPath->setText(path);
//    ui->lineEditTempPath->setCursorPosition(0);
    ui->lineEditTempPath->setToolTip(path);
    m_oBrowsePath = path;
}

void BusnessSetting::slotsChange()
{
    //qDebug()<<"BusnessSetting::slotsChange start --";
    int changeStatus = false; //状态为true,有界面上的选项被更改

    if (m_oCopyright != ui->lineEditCopyright->text()) {
        m_oCopyright = ui->lineEditCopyright->text();
        changeStatus = true;
    }
    if (m_oPreparer != ui->lineEditPreparer->text()){
        m_oPreparer = ui->lineEditPreparer->text();
        changeStatus = true;
    }
    if (m_oVolumnID != ui->lineEditVolumnID->text()) {
        m_oVolumnID = ui->lineEditVolumnID->text();
        changeStatus = true;
    }
    if (m_oPublisher != ui->lineEditPublisher->text()) {
        m_oPublisher = ui->lineEditPublisher->text();
        changeStatus = true;
    }
    if (m_oBrowsePath != m_oTemporaryPth) {
        m_oBrowsePath = m_oTemporaryPth;
        changeStatus = true;
    }
    //if (m_bClean != ui->checkBoxBunerClean->isChecked()) break;
    //if (m_bClean != ui->checkBoxClean->isChecked()) break;
    if (m_bCloseSession != ui->checkBoxCloseSeeion->isChecked()) {
        m_bCloseSession = ui->checkBoxCloseSeeion->isChecked();
        changeStatus = true;
    }
    if (m_bCreateISO != ui->checkBoxCreateISO->isChecked()) {
        m_bCreateISO = ui->checkBoxCreateISO->isChecked();
        changeStatus = true;
    }
    if (m_bVerfication != ui->checkBoxVerfication->isChecked()) {
        m_bVerfication = ui->checkBoxVerfication->isChecked();
        changeStatus = true;
    }
    //if (m_bOpen != ui->checkBoxOpen->isChecked()) break;
    if (m_oSpeeds.size() && ui->comboBoxBurnSpeed->currentIndex() >= 0) {
        if (m_iSpeed != m_oSpeeds.at(ui->comboBoxBurnSpeed->currentIndex())) {
            m_iSpeed = m_oSpeeds.at(ui->comboBoxBurnSpeed->currentIndex());
            changeStatus = true;
        }
    }
    if (m_oBurnFormat.size() && ui->comboBoxBurnFormat->currentIndex() >= 0) {
        if (m_SBurnFormat != m_oBurnFormat.at(ui->comboBoxBurnFormat->currentIndex())) {
            m_SBurnFormat = m_oBurnFormat.at(ui->comboBoxBurnFormat->currentIndex());
            changeStatus = true;
        }
    }
    if (changeStatus) {
        ensureBtnStateChanged(true);
    } else {
        ensureBtnStateChanged(false);
    }
    
    /*
    qDebug()<<"m_oBurnFormat.size()==["<<m_oBurnFormat.size()<<"]";
    qDebug()<<"m_SBurnFormat == ["<<m_SBurnFormat<<"]";
    qDebug()<<"ui->comboBoxBurnFormat->currentIndex() == [" << ui->comboBoxBurnFormat->currentIndex()<<"]";
    qDebug()<<"";
    qDebug()<<"m_oSpeeds.size()==["<<m_oSpeeds.size()<<"]";
    qDebug()<<"m_iSpeed == ["<<m_iSpeed<<"]";
    qDebug()<<"ui->comboBoxBurnSpeed->currentIndex() == [" << ui->comboBoxBurnSpeed->currentIndex()<<"]";
    qDebug()<<"";
    qDebug()<<"do-changed(true)";
    qDebug()<<"BusnessSetting::slotsChange end --";
    */
}

void BusnessSetting::slotsBrowse()
{
    QString testPath;
    //ui->btnBrowse->setIcon(QIcon::fromTheme("folder-open"));
    m_oBrowsePath = QFileDialog::getExistingDirectory(this, _("Browse"), m_oBrowsePath);
    if (!m_oBrowsePath.isEmpty())
    {
        testPath = m_oBrowsePath + "/.t/.k";
        QDir dir(testPath);
        if (dir.mkpath(testPath))
        {
            dir.removeRecursively();
            setTemporaryPath(m_oBrowsePath);
        }
        else
        {
            QMessageBox::critical(this, _("Invalid path"),
                                  _("Cannot choose a read "
                                    "only path %1 to "
                                    "temporary path").arg(m_oBrowsePath));
            m_oBrowsePath = m_oTemporaryPth;
        }
    }
}

void BusnessSetting::slotsAccept()
{
    //qDebug()<<"BusnessSetting::slotsAccept()  start----------";
    DataCDROM *cdrom = static_cast<DataCDROM *>(m_oCDROM);
    if (!cdrom) return;
    //cdrom->use();
    cdrom->preparer(ui->lineEditPreparer->text());
    cdrom->publisher(ui->lineEditPublisher->text());
    cdrom->volumnID(ui->lineEditVolumnID->text());
    cdrom->copyright(ui->lineEditCopyright->text());
    cdrom->tempPath(m_oBrowsePath);
    if (cdrom->isCDROM())
    {

        cdrom->speed(m_oSpeeds.at(ui->comboBoxBurnSpeed->currentIndex()));
        cdrom->burnFormat(m_oBurnFormat.at(ui->comboBoxBurnFormat->currentIndex()));
        //cdrom->clean(ui->checkBoxBunerClean->isChecked());
        cdrom->closeSession(ui->checkBoxCloseSeeion->isChecked());
        cdrom->createISO(ui->checkBoxCreateISO->isChecked());
        cdrom->verficationData(ui->checkBoxVerfication->isChecked());
        emit g_user_signal->changeBtnBusnessName();
        //qDebug()<<"BusnessSetting::slotsAccept  speed("<<m_oSpeeds.at(ui->comboBoxBurnSpeed->currentIndex())<<")";
        //qDebug()<<"BusnessSetting::slotsAccept  burnFormat("<<m_oBurnFormat.at(ui->comboBoxBurnFormat->currentIndex())<<")";


    }
    else
    {
        //cdrom->clean(ui->checkBoxClean->isChecked());
        //cdrom->setOpen(ui->checkBoxOpen->isChecked());
    }

    //cdrom->release();
    disconnect(MODAL, SIGNAL(accepted()), this, SLOT(slotsAccept()));

    //qDebug()<<"BusnessSetting::slotsAccept()  end-------------";
}

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

void BusnessSetting::uiAdjust(){
    ui->scrollArea->setFrameShape(QFrame::NoFrame);
    //ui->scrollAreaWidgetContents->setContentsMargins(0,0,0,0);
    ui->verticalLayout_6->setContentsMargins(0,0,7,0);
    ui->verticalLayout_2->setContentsMargins(16,0,0,0);
    ui->lineEditVolumnID->setFixedWidth(251+29);
    ui->lineEditCopyright->setFixedWidth(251+29);
    ui->lineEditPreparer->setFixedWidth(251+29);
    ui->lineEditTempPath->setFixedWidth(251+29);
    ui->lineEditPublisher->setFixedWidth(251+29);
    ui->comboBoxBurnSpeed->setFixedWidth(251+29);
    ui->comboBoxBurnFormat->setFixedWidth(251+29);

    initTempPathLineEdit();
}

void BusnessSetting::initTempPathLineEdit()
{
    // 在QLineEdit中集成一个可点击图标
    ui->lineEditTempPath->setTextMargins(0, 0, 36, 0);
    ui->lineEditTempPath->setReadOnly(true);
    QHBoxLayout *searchLayout = new QHBoxLayout(ui->lineEditTempPath);
    searchLayout->setMargin(5);
    searchLayout->setSpacing(0);
    IConLabel *buttonBrowse = new IConLabel;
    buttonBrowse->setToolTip(_("Browse"));
    buttonBrowse->setFixedSize(24, 24);
    buttonBrowse->setThemeIconSchema("folder-visiting-symbolic", ":/folder-visiting-symbolic.svg");
    searchLayout->addWidget(buttonBrowse);
    searchLayout->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    connect(buttonBrowse, &IConLabel::clicked, this, [=]() {
        MultiSelectionFileDialog selectPathDialog(this);
        selectPathDialog.setExtendedSelection();
        selectPathDialog.setDirectory(QDir::currentPath());
        selectPathDialog.setFileMode(QFileDialog::DirectoryOnly);
        selectPathDialog.setWindowTitle(_("Please select a path"));
        selectPathDialog.setWindowIcon(QIcon::fromTheme("burner"));
        kdk::UkuiStyleHelper::self()->removeHeader(&selectPathDialog);
        if (selectPathDialog.exec()) {
            QStringList selectFiles = selectPathDialog.selectedFiles();
            if (!selectFiles.isEmpty()) {
                QString fileName = selectFiles.at(0);
                ui->lineEditTempPath->setText(fileName);
                ui->lineEditTempPath->setToolTip(fileName);
                m_oBrowsePath = fileName;
            }
        }
    });
}

void BusnessSetting::paintEvent(QPaintEvent *event)
{
    QPalette pal = ui->line->palette();
    if ("ukui-black" == MAIN->theme()) {
        pal.setColor(QPalette::Dark, QColor("#37373B"));
        ui->line->setFrameShadow(QFrame::Plain);
        ui->line_2->setFrameShadow(QFrame::Plain);
        ui->line_3->setFrameShadow(QFrame::Plain);
        ui->line_4->setFrameShadow(QFrame::Plain);
    } else {
        pal.setColor(QPalette::Dark, QColor("#F2F2F2"));
        ui->line->setFrameShadow(QFrame::Sunken);
        ui->line_2->setFrameShadow(QFrame::Sunken);
        ui->line_3->setFrameShadow(QFrame::Sunken);
        ui->line_4->setFrameShadow(QFrame::Sunken);
    }
    ui->line->setPalette(pal);
    ui->line_2->setPalette(pal);
    ui->line_3->setPalette(pal);
    ui->line_4->setPalette(pal);

    QWidget::paintEvent(event);
}
