//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Beam/BeamDistributionItem.cpp
//! @brief     Implements class BeamDistributionItem.
//!
//! @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/Beam/BeamDistributionItem.h"
#include "Base/Util/Assert.h"

namespace {
namespace Tag {

const QString BeamDistribution("Distribution");

} // namespace Tag
} // namespace


BeamDistributionItem::BeamDistributionItem(double scale)
    : m_scale(scale)
{
    m_distribution.simpleInit("Distribution", "", DistributionCatalog::Type::None);
}

BeamDistributionItem::~BeamDistributionItem() = default;

void BeamDistributionItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeTaggedElement(w, Tag::BeamDistribution, m_distribution);
}

void BeamDistributionItem::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::BeamDistribution) {
            ASSERT(distributionItem());
            // keep the same limits after re-creating and reading the item
            const RealLimits old_limits = distributionItem()->center().limits();
            XML::readTaggedElement(r, tag, m_distribution);
            ASSERT(distributionItem());
            distributionItem()->center().setLimits(old_limits);
        } else
            r->skipCurrentElement();
    }
}

double BeamDistributionItem::centralValue() const
{
    return distributionItem()->center().dVal();
}

void BeamDistributionItem::resetToValue(double value)
{
    auto* d = new DistributionNoneItem();
    d->mean().setDVal(value);
    m_distribution.setCertainItem(d);
}
