//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Canvas/ProjectedGraphsCanvas.cpp
//! @brief     Implements class ProjectedGraphsCanvas.
//!
//! @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/Canvas/ProjectedGraphsCanvas.h"
#include "GUI/Model/Data/Data2DItem.h"
#include "GUI/View/Plotter/ProjectionsPlot.h"
#include <QVBoxLayout>

namespace {

enum TabID { horiz = 0, vertic = 1 };

} // namespace


ProjectedGraphsCanvas::ProjectedGraphsCanvas(QWidget* parent)
    : QWidget(parent)
    , m_x_projection(new ProjectionsPlot(Qt::Horizontal))
    , m_y_projection(new ProjectionsPlot(Qt::Vertical))
    , m_tab_widget(new QTabWidget)
{
    auto* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    m_tab_widget->setTabPosition(QTabWidget::North);
    m_tab_widget->insertTab(Qt::Horizontal, m_x_projection, "Horizontal");
    m_tab_widget->insertTab(Qt::Vertical, m_y_projection, "Vertical");

    layout->addWidget(m_tab_widget);

    setConnected(true);
}

void ProjectedGraphsCanvas::setData2DItem(Data2DItem* data_item)
{
    m_x_projection->setData2DItem(data_item);
    m_y_projection->setData2DItem(data_item);
}

void ProjectedGraphsCanvas::disconnectItem()
{
    m_x_projection->disconnectItems();
    m_y_projection->disconnectItems();
}

void ProjectedGraphsCanvas::onActivityChanged(Canvas2DMode::Flag mode)
{
    setConnected(false);

    if (mode == Canvas2DMode::HORIZONTAL_PRJN)
        m_tab_widget->setCurrentIndex(::TabID::horiz);
    else if (mode == Canvas2DMode::VERTICAL_PRJN)
        m_tab_widget->setCurrentIndex(::TabID::vertic);

    setConnected(true);
}

void ProjectedGraphsCanvas::onMarginsChanged(double left, double right)
{
    m_x_projection->onMarginsChanged(left, right);
    m_y_projection->onMarginsChanged(left, right);
}

void ProjectedGraphsCanvas::onTabChanged(int tab_index)
{
    if (tab_index == ::TabID::horiz)
        emit changeActivityRequest(Canvas2DMode::HORIZONTAL_PRJN);
    else if (tab_index == ::TabID::vertic)
        emit changeActivityRequest(Canvas2DMode::VERTICAL_PRJN);
}

void ProjectedGraphsCanvas::setConnected(bool isConnected)
{
    if (isConnected)
        connect(m_tab_widget, &QTabWidget::currentChanged, this,
                &ProjectedGraphsCanvas::onTabChanged);
    else
        disconnect(m_tab_widget, &QTabWidget::currentChanged, this,
                   &ProjectedGraphsCanvas::onTabChanged);
}
