#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFontDatabase>
#include <QMessageBox>
#include <QMovie>
#include <QMutexLocker>
#include <QPaintEvent>
#include <QPainter>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow),
      bottomRightPosition(QRect(530,505,250,40)),
      offlinePosition(240,340,300,40)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
    background.load(":/resource/SSJ_backgroundDarkSM.png");

    timer = new QTimer;
}

void MainWindow::paintEvent(QPaintEvent*) {
    QPainter painter(this);
       painter.setRenderHint(QPainter::Antialiasing);

       QPainterPath path;
       path.addRoundedRect(rect(), 8, 8);
       painter.setClipPath(path);

       if (!background.isNull())
       {
           int x = (width() - background.width()) / 2;
           int y = (height() - background.height()) / 2;
           painter.drawPixmap(x, y, background);
       }
}

void MainWindow::initialize(ResourceManager *resourceManager)
{
    bindConnection();
    this->resourceManager = resourceManager;
    ui->LanguageWidget->hide();

}

void MainWindow::setStartState()
{
    show();
    setInlineDebug(tr("Инициализация..."));
    QString title = tr("Тренажер процедур технического обслуживания самолета RRJ-95NEW-100");
    ui->headerLabel->setText(title);
    ui->versionLayoutWidget->hide();
    setUpUi();
}

void MainWindow::updateInitInformation(QString fullSize,QString currentSize)
{
    QString info = tr("Инициализация...");
    info.append(currentSize);
    info.append("/");
    info.append(fullSize);
    setInlineDebug(info);
}

void MainWindow::bindConnection()
{
    connect(timer,&QTimer::timeout,this,&MainWindow::slotDisableNotify);
}

void MainWindow::loadCompleteState()
{
    ui->inlineTextDebug->setText(tr("Обновление завершено"));
    ui->offlineStartButton->setEnabled(true);
    ui->autostartCheckBox->hide();
    ui->offlineStartButton->show();
}

bool MainWindow::getIsAutoStart()
{
    return ui->autostartCheckBox->isChecked();
}

void MainWindow::setLastVersionState()
{
    setInlineDebug(tr("Установлена последняя версия"));
    ui->unsafeChangingButton->hide();
    ui->offlineStartButton->setEnabled(true);
}

void MainWindow::setNeedUpdateState(const QString& notifyText)
{
    setInlineDebug(notifyText);
    ui->autostartCheckBox->show();
}

void MainWindow::serverBlocked()
{
    ui->notificationLabel->show();
    QPalette palette = ui->notificationLabel->palette();
    QColor orangeColor(255,165,0);
    palette.setColor(ui->notificationLabel->foregroundRole(),orangeColor);
    ui->notificationLabel->setText(tr("Сервер заблокирован"));

    ui->notificationLabel->setPalette(palette);
    timer->start(3000);
}

void MainWindow::setLoginSuccessState()
{
    ui->settingsButton->hide();
    ui->offlineStartButton->show();
    ui->versionLayoutWidget->show();
}

void MainWindow::setLoginFailedState()
{
    ui->notificationLabel->setText(tr("Неверный логин/пароль"));
    timer->setInterval(3000);
    timer->start();

    QPalette palette = ui->notificationLabel->palette();
    palette.setColor(ui->notificationLabel->foregroundRole(), Qt::red);

    ui->notificationLabel->setPalette(palette);
    ui->notificationLabel->show();
}

void MainWindow::setStartOfflineButton(bool isAvailable)
{
    ui->offlineStartButton->setEnabled(isAvailable);
}

void MainWindow::setClientVersionName(const QString& versionName)
{
    ui->valueClientVersion->setText(versionName);
}


void MainWindow::showConnectionEmpty()
{
    QPalette palette = ui->notificationLabel->palette();
    palette.setColor(ui->notificationLabel->foregroundRole(),Qt::red);
    ui->notificationLabel->setText(tr("Соединение отсутсвует"));
    ui->offlineStartButton->show();
    ui->offlineStartButton->setGeometry(offlinePosition);
    ui->offlineStartButton->raise();
    ui->settingsButton->show();
    ui->unsafeChangingButton->hide();
}

void MainWindow::disableUnsaveButton(bool flag)
{
    if(!flag) ui->unsafeChangingButton->show();
    else ui->unsafeChangingButton->hide();
}

void MainWindow::slotConnectionState(bool flag)
{
    ui->notificationLabel->show();
    QPalette palette = ui->notificationLabel->palette();
    ui->versionLayoutWidget->hide();

    setInlineDebug("");

    if(flag)
    {
        palette.setColor(ui->notificationLabel->foregroundRole(),Qt::green);
        ui->notificationLabel->setText(tr("Соединение установлено"));

        ui->offlineStartButton->show();
        ui->offlineStartButton->setGeometry(bottomRightPosition);
    }
    else
    {
        showConnectionEmpty();
    }

    ui->notificationLabel->setPalette(palette);
    timer->start(3000);
}

void MainWindow::slotServerDisconnect()
{
    ui->autostartCheckBox->hide();
    ui->inlineTextDebug->setText("");
    slotConnectionState(false);
}

void MainWindow::slotDisableNotify()
{
    ui->notificationLabel->hide();

    QPalette palette = ui->notificationLabel->palette();
    palette.setColor(ui->notificationLabel->foregroundRole(), Qt::black);

    ui->notificationLabel->setPalette(palette);
    timer->stop();
}

void MainWindow::showOfflineButton(bool flag)
{
    if (flag)
        ui->offlineStartButton->show();
    else
        ui->offlineStartButton->hide();
}

void MainWindow::on_settingsButton_clicked()
{
    emit sigShowSettings(true);
    ui->offlineStartButton->hide();
}

void MainWindow::on_languageComboBox_activated(const QString &arg1)
{
    emit sigChangeLanguage(arg1);
    ui->retranslateUi(this);
}

void MainWindow::loadToServer()
{
    ui->mainFrame->show();
    ui->inlineTextDebug->setText(tr("Отправка файлов..."));
    ui->offlineStartButton->setEnabled(false);
    ui->unsafeChangingButton->hide();
}

void MainWindow::undoCurrentChanges()
{
    ui->mainFrame->show();
    ui->offlineStartButton->setEnabled(false);
    ui->unsafeChangingButton->hide();
}

void MainWindow::on_unsafeChangingButton_clicked()
{
    emit sigShowUpdateInfo();
}

void MainWindow::on_exitButton_clicked()
{
    emit sigExit();
    delete ui;

    exit(0);
}

void MainWindow::slotShowUpdateInfo()
{
    ui->unsafeChangingButton->show();
    ui->offlineStartButton->setGeometry(bottomRightPosition);
}

void MainWindow::setUpUi()
{
    ui->notificationLabel->hide();
    ui->unsafeChangingButton->hide();

    ui->offlineStartButton->show();
    ui->offlineStartButton->setEnabled(false);
    ui->offlineStartButton->setGeometry(bottomRightPosition);

    ui->settingsButton->setIcon(*resourceManager->getSettingsIcon());

    QSize cautionIconSize(30,30);
    ui->unsafeChangingButton->setIcon(*resourceManager->getUnsavedIcon());
    ui->unsafeChangingButton->setIconSize(cautionIconSize);

    QSize iconSize(20,20);
    ui->exitButton->setIcon(*resourceManager->getCloseIcon());
    ui->exitButton->setIconSize(iconSize);

    ui->displayGroupWidget->show();
    ui->autostartCheckBox->hide();
}

void MainWindow::slotCommonWidgetState()
{
    disableUnsaveButton(true);
    setInlineDebug(tr("Загрузка..."));
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
    {
        if (!entryWidget->getLoginWidgetIsHidden())
        {
            emit sigTryLogin();
        }
    }
}

void MainWindow::showMainFrame(bool flag)
{
    if (flag) ui->mainFrame->show();
    else ui->mainFrame->hide();
}

void MainWindow::setInlineDebug(QString value)
{
    ui->inlineTextDebug->setText(value);
}

void MainWindow::setServerVersion(StreamingVersionData *version)
{
    ui->valueServerVersion->setText(version->getViewName());
}

QHBoxLayout *MainWindow::getDisplayLayout() const
{
    return ui->displayLayout;
}

void MainWindow::addWidgetToChangeGroup(CommonButtonGroupWidget *commonWidgetGroup)
{
    ui->changButtonGroup->addWidget(commonWidgetGroup);
}

void MainWindow::addWidgetToInteractiveGroup(EntryWidget *entryWidget)
{
    ui->interactiveGroup->addWidget(entryWidget);
    this->entryWidget = entryWidget;
}

void MainWindow::setLoadSettings(ServerSettings *serverSettings)
{
    ui->retranslateUi(this);

    ui->languageComboBox->setCurrentText(serverSettings->Language);
    ui->autostartCheckBox->setChecked(serverSettings->isAutoStart);
}

void MainWindow::on_offlineStartButton_clicked()
{
    emit sigStartOffline();
}
