//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Toplevel/ProjectsView.cpp
//! @brief     Implements class ProjectsView
//!
//! @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/Toplevel/ProjectsView.h"
#include "GUI/Support/Util/Path.h"
#include "GUI/View/Project/ProjectManager.h"
#include "GUI/View/Tool/GroupBoxCollapser.h"
#include "GUI/View/Tool/LayoutUtil.h"
#include "ui_ProjectsView.h"
#include <QCommandLinkButton>
#include <QDesktopServices>
#include <QDir>
#include <QUrl>

ProjectsView::ProjectsView(QWidget* parent)
    : QWidget(parent)
    , m_ui(new Ui::ProjectsView)
{
    m_ui->setupUi(this);

    GroupBoxCollapser::installIntoGroupBox(m_ui->groupBox_2);

    QPalette palette = this->palette();
    palette.setColor(QPalette::Window, Qt::white);
    setPalette(palette);

    connect(m_ui->newButton, &QPushButton::clicked, projectManager(), &ProjectManager::newProject);
    connect(m_ui->openButton, &QPushButton::clicked, [this]() { projectManager()->openProject(); });
    connect(projectManager(), &ProjectManager::recentListModified, this,
            &ProjectsView::updateRecentProjectPanel);

    updateRecentProjectPanel();
}

ProjectManager* ProjectsView::projectManager()
{
    return ProjectManager::instance();
}

void ProjectsView::updateRecentProjectPanel()
{
    GUI::Util::Layout::clearLayout(m_ui->recentProjectsLayout);

    for (const auto& file : projectManager()->recentProjects()) {
        auto* button = new QCommandLinkButton;
        button->setText(QFileInfo(file).baseName());
        button->setDescription(GUI::Base::Path::withTildeHomePath(QDir::toNativeSeparators(file)));
        button->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
        connect(button, &QCommandLinkButton::clicked,
                [this, file] { projectManager()->openProject(file); });

        m_ui->recentProjectsLayout->addWidget(button);
    }
    m_ui->recentProjectsLayout->addStretch(1);
}
