#include "modaldialog.h"
#include "ui_modaldialog.h"
#include "src/frame/xatom-helper.h"
#include "src/frame/logger.h"
#include "src/po/translation.h"
#include "src/model/logicmain.h"
#include "src/frame/signals.h"
#include <QMoveEvent>
#include <QPushButton>
#include <QCoreApplication>
#include <QDebug>
#include <ukuistylehelper.h>
#include "src/view/mainwindow.h"
#include <windowmanager/windowmanager.h>
#include <QDesktopWidget>
using namespace kdk;

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

ModalDialog::ModalDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ModalDialog)
{
    QFont f;
    ui->setupUi(this);
    //判断是否是wayland环境
    if(QString(qgetenv("XDG_SESSION_TYPE")) == "wayland") {
        m_bIsWayland = true;
    } else {
        m_bIsWayland = false;
        MotifWmHints hints;
        hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
        hints.functions = MWM_FUNC_ALL;
        hints.decorations = MWM_DECOR_BORDER;
        XAtomHelper::getInstance()->setWindowMotifHint(winId(), hints);
    }
    setAttribute(Qt::WA_ShowModal, true);

    ui->title->onlyShowInDialog();
    connect(ui->title, SIGNAL(close()), this, SLOT(slotsClose()));
    connect(this, SIGNAL(windowIconChanged(QIcon)), ui->title, SLOT(onWindowIconChange(QIcon)));
    connect(this, SIGNAL(windowTitleChanged(QString)), ui->title, SLOT(onWindowTitleChange(QString)));

    connect(this, SIGNAL(info(QString)), LOGGER, SLOT(info(QString)));
    connect(this, SIGNAL(warn(QString)), LOGGER, SLOT(warn(QString)));
    connect(this, SIGNAL(error(QString)), LOGGER, SLOT(error(QString)));
    connect(this, SIGNAL(debug(QString)), LOGGER, SLOT(debug(QString)));

    //图标库主题的刻录图片名换为burner
    //setWindowIcon(QIcon::fromTheme("disk-burner"));
    setWindowIcon(QIcon::fromTheme("burner"));
    connect(ui->progress, SIGNAL(title(QString)), this, SLOT(slotsTitle(QString)));
    connect(g_user_signal, &GlobalUserSignal::iconChange, [=](QIcon icon){
        setWindowIcon(icon);
    });

    f = ui->btnBox->font();
    f.setPixelSize(14);
    ui->btnBox->setFont(f);
	ui->btnBox->clear();
    m_oCancelBtn = ui->btnBox->addButton(_("Cancel"), QDialogButtonBox::AcceptRole);
    m_oEnsureBtn = ui->btnBox->addButton(_("OK"), QDialogButtonBox::RejectRole);
}

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

QWidget *ModalDialog::showPage(int page)
{
    m_bCanClose = true;
    disconnect(this, SIGNAL(accepted()), ui->busnessSetting, SLOT(slotsAccept()));
    disconnect(this, SIGNAL(accepted()), ui->diskcheck, SLOT(accept()));
    //QCoreApplication::processEvents();弹窗界面递归导致闪退，所以去掉
    switch (page)
    {
    case Progress:
        m_oCancelBtn->show();
        m_oEnsureBtn->hide();
        setFixedSize(450, 230);
        ui->title->onlyVisibleClose(false);
        //ui->btnBox->setStandardButtons(QDialogButtonBox::Cancel);
        //ui->btnBox->button(QDialogButtonBox::Cancel)->setText(_("Cancel"));
        break;
    case Tip:
        setFixedSize(450, 230);
        ui->title->onlyVisibleClose(true);
        //ui->btnBox->setStandardButtons(QDialogButtonBox::NoButton);
        //ui->btnBox->setStandardButtons(QDialogButtonBox::Ok);
        m_oEnsureBtn->show();
		m_oCancelBtn->hide();
        break;
    case BusnessSetting:
        m_oEnsureBtn->show();
        m_oCancelBtn->show();
        setFixedSize(405, 530);
        ui->verticalLayout->setContentsMargins(0,0,0,16);
        ui->verticalLayout_2->setSpacing(22);
        ui->btnBox->setFixedHeight(36);
        ui->btnBox->setContentsMargins(0,0,24,0);
        ui->title->onlyVisibleClose(true);
        connect(ui->busnessSetting, SIGNAL(title(QString)), this, SLOT(slotsTitle(QString)));
        connect(this, SIGNAL(accepted()), ui->busnessSetting, SLOT(slotsAccept()));
        //connect(ui->busnessSetting, SIGNAL(changed(bool)), ui->btnBox->button(QDialogButtonBox::Ok), SLOT(setEnabled(bool)));
        connect(ui->busnessSetting, SIGNAL(ensureBtnStateChanged(bool)), m_oEnsureBtn, SLOT(setEnabled(bool)));
        connect(ui->busnessSetting, SIGNAL(cancelBtnStateChanged(bool)), m_oCancelBtn, SLOT(setEnabled(bool)));
        break;
    case DataSetting:
        m_oEnsureBtn->show();
        m_oCancelBtn->show();
        m_oCancelBtn->setEnabled(true);
        setFixedSize(376,441);
        ui->verticalLayout->setContentsMargins(0,0,0,16);
        ui->btnBox->setContentsMargins(0,0,58,0);
        ui->title->onlyVisibleClose(true);
        connect(ui->dataSetting, SIGNAL(title(QString)), this, SLOT(slotsTitle(QString)));
        connect(this, SIGNAL(accepted()), ui->dataSetting, SLOT(accept()));
        ui->dataSetting->load();
        break;
    case DiskCheck:
        m_oEnsureBtn->show();
        m_oCancelBtn->hide();
        setFixedSize(450, 492);
        ui->verticalLayout_2->setContentsMargins(9,9,24,12);
        ui->btnBox->setContentsMargins(0,0,0,0);
        ui->title->onlyVisibleClose(true);
        slotsTitle(_("Disk Check"));
        connect(ui->diskcheck, SIGNAL(change(bool)), m_oEnsureBtn, SLOT(setEnabled(bool)));
        connect(this, SIGNAL(accepted()), ui->diskcheck, SLOT(accept()));
        ui->diskcheck->change(ui->diskcheck->check());
        break;
    }
    ui->showPage->setCurrentIndex(page);
    return ui->showPage->currentWidget();
}

void ModalDialog::cancelEnable(bool b)
{
    m_bCanClose = false;
    //ui->btnBox->button(QDialogButtonBox::Cancel)->setEnabled(b);
    m_oCancelBtn->setEnabled(b);
}

void ModalDialog::updatePosition(QPoint p)
{   
    m_oMainPos = p;
}

void ModalDialog::show()
{
    if (this->isWayland())
        kdk::UkuiStyleHelper::self()->removeHeader(this);
    QDialog::show();
    if(!this->isWayland()){
        QPoint position = MainWindow::Instance()->frameGeometry().topLeft();
        move(position.x()+(MainWindow::Instance()->width()-width())/2, position.y()+(MainWindow::Instance()->height()-height())/2);
        kdk::WindowManager::setGeometry(windowHandle(),geometry());
    }
}

void ModalDialog::paintEvent(QPaintEvent *event)
{
    QPalette pal = palette();

    //QCoreApplication::processEvents();弹窗界面递归导致栈资源用完闪退，所以去掉

    if ("ukui-black" == MAIN->theme())
        pal.setBrush(QPalette::Background, QColor("#1D1D1D"));
    else
        pal.setBrush(QPalette::Background, QColor("#FFFFFF"));
    setPalette(pal);
    //setWindowIcon(QIcon::fromTheme("burner"));
    QDialog::paintEvent(event);
}

void ModalDialog::closeEvent(QCloseEvent *event)
{
    slotsClose();
    QDialog::closeEvent(event);
}

void ModalDialog::slotsTitle(QString title)
{
    setWindowTitle(_("Burner")/* + " - " + title*/);
}

void ModalDialog::slotsClose()
{
	qDebug()<<__func__<<__LINE__;
    disconnect(this, SIGNAL(accepted()), ui->diskcheck, SLOT(accept()));
    if (!m_bCanClose) return;
    switch (ui->showPage->currentIndex())
    {
    case Progress:
        //if (ui->btnBox->button(QDialogButtonBox::Cancel)->isEnabled())
        if (m_oCancelBtn->isEnabled())
        {
            reject();
        }
        break;
    case Tip:
        reject();
        break;
    case BusnessSetting:
        close();
        disconnect(this, SIGNAL(accepted()), ui->dataSetting, SLOT(accept()));
        break;
    case DataSetting:
        disconnect(ui->dataSetting, SIGNAL(title(QString)), this, SLOT(slotsTitle(QString)));
        disconnect(this, SIGNAL(accepted()), ui->dataSetting, SLOT(accept()));
        //disconnect(ui->dataSetting, SIGNAL(change(bool)), ui->btnBox->button(QDialogButtonBox::Ok), SLOT(setEnabled(bool)));
        disconnect(ui->dataSetting, SIGNAL(change(bool)), m_oEnsureBtn, SLOT(setEnabled(bool)));
        close();
        break;
    case DiskCheck:
        disconnect(ui->dataSetting, SIGNAL(change(bool)), m_oEnsureBtn, SLOT(setEnabled(bool)));
        //disconnect(ui->diskcheck, SIGNAL(change(bool)), ui->btnBox->button(QDialogButtonBox::Ok), SLOT(setEnabled(bool)));
        disconnect(this, SIGNAL(accepted()), ui->diskcheck, SLOT(accept()));
        close();
        break;
    }
}

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