//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/View/DatafilesSelector.cpp
//! @brief     Implements class DatafilesSelector.
//!
//! @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/View/DatafilesSelector.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Data/DataItem.h"
#include "GUI/Model/File/DatafilesSet.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/View/IO/DataLoader.h"
#include "GUI/View/Modelview/SetView.h"
#include "GUI/View/Setup/ActionFactory.h"
#include "GUI/View/Widget/StyledToolbar.h"
#include <QBoxLayout>

DatafilesSelector::DatafilesSelector()
    : m_set(gDoc->datafilesRW())
    , m_qlistview(new SetView(m_set))
{
    setMinimumWidth(200);
    setMaximumWidth(300);
    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
    setWindowTitle("DatafilesSelector");

    auto* layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    setLayout(layout);

    auto* toolbar = new StyledToolbar;
    layout->addWidget(toolbar);
    toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    createActions(toolbar);

    layout->addWidget(m_qlistview);

    connect(m_set, &AbstractSetModel::setChanged, this, &DatafilesSelector::updateActions);
    updateActions();
}

void DatafilesSelector::createActions(QToolBar* toolbar)
{
    auto* import1dData_action = new QAction(this);
    toolbar->addAction(import1dData_action);
    import1dData_action->setText("1D");
    import1dData_action->setIcon(QIcon(":/images/shape-square-plus.svg"));
    import1dData_action->setToolTip("Import 1D data");
    connect(import1dData_action, &QAction::triggered,
            [this] { m_set->add_items(IO::importData1D()); });

    auto* import2dData_action = new QAction(this);
    toolbar->addAction(import2dData_action);
    import2dData_action->setText("2D");
    import2dData_action->setIcon(QIcon(":/images/shape-square-plus.svg"));
    import2dData_action->setToolTip("Import 2D data");
    connect(import2dData_action, &QAction::triggered,
            [this] { m_set->add_items(IO::importData2D()); });

    m_rm_action = ActionFactory::createRemoveAction("data file");
    toolbar->addAction(m_rm_action);
    connect(m_rm_action, &QAction::triggered, m_set, &DatafilesSet::delete_current);
}

void DatafilesSelector::updateActions()
{
    bool enabled = m_set->currentIndex() != size_t(-1);
    m_rm_action->setEnabled(enabled);
}
