//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Detector/OffspecDetectorItem.cpp
//! @brief     Implements class OffspecDetectorItem.
//!
//! @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/Model/Detector/OffspecDetectorItem.h"
#include "Base/Const/Units.h"
#include "Device/Detector/OffspecDetector.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString AlphaAxis("AlphaAxis");
const QString PhiAxis("PhiAxis");
const QString BaseData("BaseData");

} // namespace Tag

} // namespace

OffspecDetectorItem::OffspecDetectorItem()
    : m_phi_axis("phi", "deg", -1, 1, RealLimits::limited(-90, 90))
    , m_alpha_axis("alpha", "deg", 0, 2, RealLimits::limited(-90, 90))
{
}

void OffspecDetectorItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeTaggedElement(w, Tag::PhiAxis, m_phi_axis);
    XML::writeTaggedElement(w, Tag::AlphaAxis, m_alpha_axis);
}

void OffspecDetectorItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::PhiAxis)
            XML::readTaggedElement(r, tag, m_phi_axis);
        else if (tag == Tag::AlphaAxis)
            XML::readTaggedElement(r, tag, m_alpha_axis);
        else
            r->skipCurrentElement();
    }
}

std::unique_ptr<OffspecDetector> OffspecDetectorItem::createOffspecDetector() const
{
    const int n_x = m_phi_axis.nbins();
    const double x_min = Units::deg2rad(m_phi_axis.min().dVal());
    const double x_max = Units::deg2rad(m_phi_axis.max().dVal());

    const int n_y = m_alpha_axis.nbins();
    const double y_min = Units::deg2rad(m_alpha_axis.min().dVal());
    const double y_max = Units::deg2rad(m_alpha_axis.max().dVal());

    return std::make_unique<OffspecDetector>(n_x, x_min, x_max, n_y, y_min, y_max);
}
