//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Plotter/HistogramPlot.cpp
//! @brief     Implements class HistogramPlot.
//!
//! @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/Plotter/HistogramPlot.h"
#include "GUI/View/Base/Fontsize.h"
#include <qcustomplot.h>

HistogramPlot::HistogramPlot(QWidget* parent)
    : QWidget(parent)
    , m_qcp(new QCustomPlot)

{
    auto* vlayout = new QVBoxLayout(this);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->addWidget(m_qcp);
    m_qcp->setAttribute(Qt::WA_NoMousePropagation, false);
    setLayout(vlayout);
    setStyleSheet("background-color:white;");

    initGraph();

    m_qcp->xAxis->setTickLabelFont(QFont(QFont().family(), GUI::Style::fontSizeSmall()));
    m_qcp->yAxis->setTickLabelFont(QFont(QFont().family(), GUI::Style::fontSizeSmall()));

    m_qcp->yAxis->setScaleType(QCPAxis::stLogarithmic);
    m_qcp->yAxis->setNumberFormat("eb");
    m_qcp->yAxis->setNumberPrecision(0);

    m_qcp->xAxis->setLabel("iteration");
    m_qcp->yAxis->setLabel("chi2");

    m_qcp->xAxis->setLabelFont(QFont(QFont().family(), GUI::Style::fontSizeRegular()));
    m_qcp->yAxis->setLabelFont(QFont(QFont().family(), GUI::Style::fontSizeRegular()));
}

void HistogramPlot::addData(double x, double y)
{
    m_qcp->graph()->addData(x, y);
    m_qcp->graph()->rescaleAxes();
    m_qcp->replot();
}

void HistogramPlot::addData(const QVector<double>& x, const QVector<double>& y)
{
    m_qcp->graph()->addData(x, y);
    m_qcp->graph()->rescaleAxes();
    m_qcp->replot();
}

void HistogramPlot::setData(const QVector<double>& x, const QVector<double>& y)
{
    m_qcp->graph()->setData(x, y);
    m_qcp->graph()->rescaleAxes();
    m_qcp->replot();
}

void HistogramPlot::clearData()
{
    m_qcp->removeGraph(m_qcp->graph());
    initGraph();
    m_qcp->replot();
}

void HistogramPlot::initGraph()
{
    m_qcp->addGraph();

    QPen pen(QColor(0, 0, 255, 200));
    m_qcp->graph()->setLineStyle(QCPGraph::lsLine);
    m_qcp->graph()->setPen(pen);
    m_qcp->graph()->setBrush(QBrush(QColor(255 / 4, 160, 50, 150)));

    auto base_size = GUI::Style::SizeOfLetterM();
    auto* axisRectangle = m_qcp->axisRect();
    axisRectangle->setAutoMargins(QCP::msTop | QCP::msBottom);
    axisRectangle->setMargins(QMargins(base_size.width() * 4, base_size.height() * 2,
                                       base_size.width() * 2, base_size.height() * 2));
}
