//  ************************************************************************************************
//
//  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>

ProjectedGraphsCanvas::ProjectedGraphsCanvas()
    : 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();
}

ProjectionsPlot* ProjectedGraphsCanvas::currentProjectionsPlot() const
{
    return dynamic_cast<ProjectionsPlot*>(m_tab_widget->currentWidget());
}

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

    if (mode == Canvas2DMode::HORIZONTAL_PRJN)
        m_tab_widget->setCurrentIndex(0);
    else if (mode == Canvas2DMode::VERTICAL_PRJN)
        m_tab_widget->setCurrentIndex(1);

    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 == 0)
        emit currentTabChanged(Canvas2DMode::HORIZONTAL_PRJN);
    else if (tab_index == 1)
        emit currentTabChanged(Canvas2DMode::VERTICAL_PRJN);
}

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