#include "log/UserOperationLog.h"
#include "guimessagedialog.h"
#include "ui_guimessagedialog.h"
#include "event/EventCenter.h"
GUIMessageDialog::GUIMessageDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GUIMessageDialog)
{
    ui->setupUi(this);
    this->setObjectName("MessageDialog");
    this->setWindowFlags (Qt :: FramelessWindowHint | Qt :: Dialog);
    this->showFullScreen ();
    ui->lbl_msg->setVisible(false);
    ui->lbl_progressicon->setVisible(false);
    ui->btn_main->setVisible(false);
    ui->btn_main->setText("OK");
    this->setWindowOpacity(0.6);
    for (int i=1; i<=6;i++)
    {
        QString str("      ");
        for(int j=0;j<i;j++)
        {
            str[j]='.';
        }
        frame.append(str);
    }
    for (int i=1; i<=6;i++)
    {
        QString str("......");
        for(int j=0;j<i;j++)
        {
            str[j]=' ';
        }
        frame.append(str);
    }
}

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

void GUIMessageDialog::timerEvent(QTimerEvent *event) {
    if (frameIndex>11) frameIndex = frameIndex % 12;
    ui->lbl_progressicon->setText(frame[frameIndex++]);
    this->update();
}

void GUIMessageDialog::stopLoading() {
    if (timerID!=-1){
        killTimer(timerID);
        timerID=-1;
    }
    disconnect(ui->btn_main,0,0,0);
    ui->lbl_progressicon->setVisible(false);
}

void GUIMessageDialog::startLoading() {
    ui->lbl_progressicon->setVisible(true);
    disconnect(ui->btn_main,0,0,0);
    connect(ui->btn_main,&QToolButton::clicked,[=](){
        if (timerID != -1){
            killTimer(timerID);
            timerID = -1;
        }
        accept();
        EventCenter::Default()->triggerEvent(GUIEvents::RequestStop, nullptr, nullptr);
        LOG_USER_OPERATION(Stop);
    });
    timerID = startTimer(100);
    ui->btn_main->setText("Stop");
    ui->btn_main->setVisible(true);

}

void GUIMessageDialog::showMessage(QString msg) {
    ui->lbl_msg->setVisible(true);
    ui->lbl_msg->setText(msg);
}

void GUIMessageDialog::showExitButton() {
    ui->btn_main->setText("OK");
    ui->btn_main->setVisible(true);
    disconnect(ui->btn_main,0,0,0);
    connect(ui->btn_main,&QToolButton::clicked,[=](){
        if (timerID != -1){
            killTimer(timerID);
            timerID = -1;
        }
        accept();
        LOG_USER_OPERATION(ConfirmError);
    });
}

void GUIMessageDialog::hideMessage() {
    ui->lbl_msg->setVisible(false);
    ui->lbl_msg->setText("");
}

void GUIMessageDialog::hideExitButton() {
    ui->btn_main->setVisible(false);
    disconnect(ui->btn_main,0,0,0);
}

void GUIMessageDialog::setOpacity(double opacity) {
    this->setWindowOpacity(opacity);
}
