//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Frame/Fit1DFrame.cpp
//! @brief     Implements class Fit1DFrame.
//!
//! @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/Frame/Fit1DFrame.h"
#include "Base/Util/Assert.h"
#include "Device/Data/DataUtil.h"
#include "Device/Data/Datafield.h"
#include "GUI/Model/Axis/AmplitudeAxisItem.h"
#include "GUI/Model/Data/Data1DItem.h"
#include "GUI/Model/Data/RangeUtil.h"
#include "GUI/Model/Job/JobsSet.h"
#include "GUI/Model/Project/DataSource.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/View/Canvas/ProgressCanvas.h"
#include "GUI/View/Canvas/SpecularPlotCanvas.h"
#include "GUI/View/Plotter/PlotStatusLabel.h"
#include "GUI/View/Plotter/SavePlot.h"
#include "GUI/View/Plotter/SpecularPlot.h"
#include "GUI/View/Setup/AxisPanel.h"
#include "GUI/View/Setup/Data1DToolbar.h"
#include "GUI/View/Setup/FrameActions.h"

Fit1DFrame::Fit1DFrame()
    : AnydataFrame(std::make_unique<DataFromJob>())
    , m_data_canvas(new SpecularPlotCanvas)
    , m_diff_canvas(new SpecularPlotCanvas)
    , m_status_label(
          new PlotStatusLabel({m_data_canvas->specularPlot(), m_diff_canvas->specularPlot()}))
{
    auto* vlayout = new QVBoxLayout;
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);

    auto* gridLayout = new QGridLayout;
    gridLayout->setContentsMargins(0, 0, 0, 0);
    gridLayout->setSpacing(0);

    gridLayout->addWidget(m_data_canvas, 0, 0, 1, -1);
    gridLayout->addWidget(m_diff_canvas, 1, 0, 1, 2);
    auto* progress_canvas = new ProgressCanvas;
    gridLayout->addWidget(progress_canvas, 1, 2, 1, 1);

    vlayout->addLayout(gridLayout);
    vlayout->addWidget(m_status_label);

    auto* hlayout = new QHBoxLayout(this);
    hlayout->setContentsMargins(0, 0, 0, 0);
    hlayout->setSpacing(0);
    hlayout->addLayout(vlayout);

    auto* axis_panel = new AxisPanel(dataSource());
    hlayout->addWidget(axis_panel);
    axis_panel->hide();

    auto* toolbar = new Data1DToolbar;
    hlayout->addWidget(toolbar);

    updateFrame();


    //... Connect signals from toolbar

    connect(toolbar->actions()->toggle_properties_panel, &QAction::triggered, axis_panel,
            &QWidget::setVisible);

    connect(toolbar->actions()->reset_view, &QAction::triggered, this,
            &Fit1DFrame::onResetViewAction);

    connect(toolbar->actions()->save_plot, &QAction::triggered, [this] {
        ASSERT(simuItem());
        GUI::Plot::savePlot(m_data_canvas->specularPlot(), simuItem()->c_field());
    });


    //... Connect model

    connect(gDoc->jobs(), &JobsSet::jobPlotContextChanged, this, &Fit1DFrame::updateFrame);
}

Fit1DFrame::~Fit1DFrame() = default;

void Fit1DFrame::updateFrame()
{
    if (!hasProperContext()) {
        hide();
        return;
    }

    GUI::Util::Ranges::setCommonRangeY(dataSource()->mainData1DItems());
    updateDiffData();
    connectItems();

    m_data_canvas->setData1DItems({simuItem(), realItem()});
    m_diff_canvas->setData1DItems({diffItem()});

    show();
}

void Fit1DFrame::updateDiffData()
{
    if (!hasProperContext())
        return;

    if (!simuItem()->c_field() || !realItem()->c_field())
        return;

    diffItem()->setDatafield(
        DataUtil::relativeDifferenceField(*simuItem()->c_field(), *realItem()->c_field()));

    // keep Y axis range up with data range
    double min = diffItem()->yMin();
    double max = diffItem()->yMax();
    if (!diffItem()->axItemY()->isLogScale() || min > 0)
        diffItem()->setYrange(min, max);
}

void Fit1DFrame::updateRealFrame()
{
    if (!hasProperContext())
        return;

    // adjust frame of real data
    realItem()->setDatafield({simuItem()->c_field()->frame(), realItem()->c_field()->flatVector()});
}

void Fit1DFrame::connectItems()
{
    // sync X range: simu --> diff
    connect(simuItem(), &DataItem::updateOtherPlots, diffItem(), &DataItem::alignXranges,
            Qt::UniqueConnection);

    // sync X range: diff --> simu/real
    connect(diffItem(), &DataItem::updateOtherPlots, simuItem(), &DataItem::alignXranges,
            Qt::UniqueConnection);

    // sync ranges between simulated and real when recomputed
    connect(simuItem(), &Data1DItem::datafieldChanged, this, &Fit1DFrame::updateRealFrame,
            Qt::UniqueConnection);

    // update diff data if simulation data changes
    connect(simuItem(), &Data1DItem::datafieldChanged, this, &Fit1DFrame::updateDiffData,
            Qt::UniqueConnection);
}

void Fit1DFrame::onResetViewAction()
{
    ASSERT(hasProperContext());

    simuItem()->resetView();
    realItem()->resetView();
    diffItem()->resetView();

    // synchronize data range between simulated and real
    GUI::Util::Ranges::setCommonRangeY(dataSource()->mainData1DItems());
    gDoc->setModified();
}

//  ************************************************************************************************
//  shortcuts
//  ************************************************************************************************

bool Fit1DFrame::hasProperContext() const
{
    return bool(realItem() && simuItem() && diffItem());
}

Data1DItem* Fit1DFrame::realItem() const
{
    return dataSource()->realData1DItem();
}

Data1DItem* Fit1DFrame::simuItem() const
{
    return dataSource()->simuData1DItem();
}

Data1DItem* Fit1DFrame::diffItem() const
{
    return dataSource()->diffData1DItem();
}
