//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Main/MainWindow.cpp
//! @brief     Implements class MainWindow.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Main/MainWindow.h"
#include "GUI/Model/Job/JobsSet.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Model/Util/Path.h"
#include "GUI/View/Base/mainwindow_constants.h"
#include "GUI/View/Main/ActionManager.h"
#include "GUI/View/Main/CentralWidget.h"
#include "GUI/View/Main/ProjectManager.h"
#include "GUI/View/Setup/FrameActions.h"
#include "GUI/View/Widget/AppConfig.h"
#include <QApplication>
#include <QDir>
#include <QMessageBox>
#include <QSettings>

MainWindow::MainWindow()
{
    m_project_manager = new ProjectManager(this);
    m_action_manager = new ActionManager(this, m_project_manager);
    m_central_widget = new CentralWidget;

    setCentralWidget(m_central_widget);

    initApplication();
    loadSettings();

    connect(gDoc.get(), &ProjectDocument::documentAboutToReopen,
            [this] { m_central_widget->currentView()->hide(); });
    connect(gDoc.get(), &ProjectDocument::documentOpened, this, &MainWindow::onDocumentOpened);

    connect(gDoc.get(), &ProjectDocument::documentOpened, m_action_manager,
            &ActionManager::updateActionEnabling);

    connect(gDoc.get(), &ProjectDocument::modifiedStateChanged, this,
            &MainWindow::onDocumentModified);

    connect(m_central_widget, &CentralWidget::currentViewChanged, m_action_manager,
            &ActionManager::onCurrentViewChanged);

    onDocumentOpened();
}

MainWindow::~MainWindow() = default;

void MainWindow::updateTitle()
{
    QString location = "not saved yet";
    if (gDoc->hasValidNameAndPath())
        location = GUI::Path::withTildeHomePath(QDir::toNativeSeparators(gDoc->projectFullPath()));
    const QString cModified = gDoc->isModified() ? "*" : "";
    setWindowTitle("BornAgain - " + cModified + gDoc->projectName() + " [" + location + "]");
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    if (gDoc->jobs()->hasUnfinishedJobs()) {
        QMessageBox::warning(this, "Cannot quit the application.",
                             "Cannot quit the application while jobs are running.\n"
                             "Cancel running jobs or wait until they are completed.");
        event->ignore();
        return;
    }
    if (m_project_manager->saveOnQuit()) {
        saveSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

void MainWindow::initApplication()
{
    setDockNestingEnabled(true);
    setAcceptDrops(true);

    setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
}

void MainWindow::loadSettings()
{
    QSettings s;
    s.beginGroup(GUI::Style::S_MAIN_WINDOW);
    resize(s.value(GUI::Style::S_WINDOW_SIZE, QSize(1000, 600)).toSize());
    move(s.value(GUI::Style::S_WINDOW_POSITION, QPoint(500, 300)).toPoint());
    s.endGroup();
    m_project_manager->loadSettings();
}

void MainWindow::saveSettings()
{
    QSettings s;
    s.beginGroup(GUI::Style::S_MAIN_WINDOW);
    s.setValue(GUI::Style::S_WINDOW_SIZE, size());
    s.setValue(GUI::Style::S_WINDOW_POSITION, pos());
    s.endGroup();
    m_project_manager->saveSettings();
    gApp->saveSettings();
    s.sync();
}

void MainWindow::onDocumentOpened()
{
    updateTitle();
    m_central_widget->updateViews();
    m_central_widget->restoreView(gDoc->viewId());
}

void MainWindow::onDocumentModified()
{
    updateTitle();
}

void MainWindow::loadProject(QString projectPath)
{
    m_project_manager->openProject(projectPath);
}
