//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Sample/InterferenceItems.cpp
//! @brief     Implements class InterferenceItem and subclasses.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2021
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/Model/Sample/InterferenceItems.h"
#include "Base/Const/Units.h"
#include "Sample/Aggregate/Interferences.h"

namespace {
namespace Tag {

const QString PositionVariance("PositionVariance");
const QString Length("Length");
const QString RotationAngle("RotationAngle");
const QString IntegrateOverXi("IntegrateOverXi");
const QString DampingLength("DampingLength");
const QString DomainSize("DomainSize");
const QString DomainSize1("DomainSize1");
const QString DomainSize2("DomainSize2");
const QString Radius("Radius");
const QString Density("Density");
const QString PeakDistance("PeakDistance");
const QString Kappa("Kappa");
const QString DecayFunction("DecayFunction");
const QString LatticeType("LatticeType");
const QString PDF("PDF");
const QString PDF1("PDF1");
const QString PDF2("PDF2");
const QString BaseData("BaseData");

} // namespace Tag
} // namespace

InterferenceItem::InterferenceItem()
{
    m_position_variance.init("PositionVariance (nm^2)",
                             "Variance of the position in each dimension", 0.0, "PositionVariance");
}

void InterferenceItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // position variance
    w->writeStartElement(Tag::PositionVariance);
    m_position_variance.writeTo(w);
    w->writeEndElement();
}

void InterferenceItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // position variance
        if (tag == Tag::PositionVariance) {
            m_position_variance.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

Interference1DLatticeItem::Interference1DLatticeItem()
{
    m_length.init("Length (nm)", "Lattice length", 20.0, "Length");
    m_rotation_angle.init(
        "Xi (deg)",
        "Rotation of lattice with respect to x-axis of reference frame (beam direction)", 0.0,
        "xi");
    m_decay_function.initWithArgs("Decay Function",
                                  "One-dimensional decay function (finite size effects)",
                                  Profile1DItemCatalog::Type::Cauchy);
}

std::unique_ptr<IInterference> Interference1DLatticeItem::createInterference() const
{
    auto result =
        std::make_unique<Interference1DLattice>(m_length, Units::deg2rad(m_rotation_angle));
    result->setDecayFunction(*m_decay_function->createProfile());
    result->setPositionVariance(m_position_variance);
    return std::unique_ptr<IInterference>(result.release());
}

void Interference1DLatticeItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    InterferenceItem::writeTo(w);
    w->writeEndElement();

    // length
    w->writeStartElement(Tag::Length);
    m_length.writeTo(w);
    w->writeEndElement();

    // rotation angle
    w->writeStartElement(Tag::RotationAngle);
    m_rotation_angle.writeTo(w);
    w->writeEndElement();

    // decay function
    w->writeStartElement(Tag::DecayFunction);
    m_decay_function.writeTo(w);
    w->writeEndElement();
}

void Interference1DLatticeItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            InterferenceItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // length
        } else if (tag == Tag::Length) {
            m_length.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // rotation angle
        } else if (tag == Tag::RotationAngle) {
            m_rotation_angle.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // decay function
        } else if (tag == Tag::DecayFunction) {
            m_decay_function.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

void Interference2DAbstractLatticeItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    InterferenceItem::writeTo(w);
    w->writeEndElement();

    // integrate over xi?
    w->writeStartElement(Tag::IntegrateOverXi);
    XML::writeAttribute(w, XML::Attrib::value, m_xi_integration);
    w->writeEndElement();

    // lattice type
    w->writeStartElement(Tag::LatticeType);
    m_lattice_type.writeTo(w);
    w->writeEndElement();
}

void Interference2DAbstractLatticeItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            InterferenceItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // integrate over xi?
        } else if (tag == Tag::IntegrateOverXi) {
            XML::readAttribute(r, XML::Attrib::value, &m_xi_integration);
            XML::gotoEndElementOfTag(r, tag);

            // lattice type
        } else if (tag == Tag::LatticeType) {
            m_lattice_type.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

Interference2DAbstractLatticeItem::Interference2DAbstractLatticeItem(bool xiIntegration)
    : m_xi_integration(xiIntegration)
{
    m_lattice_type.initWithArgs("Lattice type", "", Lattice2DItemCatalog::Type::Basic);
    m_lattice_type.setCertainItem(new HexagonalLattice2DItem());
}

// --------------------------------------------------------------------------------------------- //

Interference2DLatticeItem::Interference2DLatticeItem()
    : Interference2DAbstractLatticeItem(false)
{
    m_decay_function.initWithArgs("Decay Function",
                                  "Two-dimensional decay function (finite size effects)",
                                  Profile2DItemCatalog::Type::Cauchy);
}

std::unique_ptr<IInterference> Interference2DLatticeItem::createInterference() const
{
    Lattice2DItem* latticeItem = latticeTypeItem();
    std::unique_ptr<Interference2DLattice> result(
        new Interference2DLattice(*latticeItem->createLattice()));

    result->setDecayFunction(*m_decay_function->createProfile());
    result->setIntegrationOverXi(xiIntegration());
    result->setPositionVariance(m_position_variance);

    return std::unique_ptr<IInterference>(result.release());
}

void Interference2DLatticeItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    Interference2DAbstractLatticeItem::writeTo(w);
    w->writeEndElement();

    // decay function
    w->writeStartElement(Tag::DecayFunction);
    m_decay_function.writeTo(w);
    w->writeEndElement();
}

void Interference2DLatticeItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            Interference2DAbstractLatticeItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // decay function
        } else if (tag == Tag::DecayFunction) {
            m_decay_function.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

Interference2DParacrystalItem::Interference2DParacrystalItem()
    : Interference2DAbstractLatticeItem(true)
{
    m_damping_length.init("Damping length (nm)",
                          "The damping (coherence) length of the paracrystal", 0.0, "dampingLen");
    m_domain_size1.init("Domain size 1 (nm)",
                        "Size of the coherent domain along the first basis vector", 20000.0,
                        "size1");
    m_domain_size2.init("Domain size 2 (nm)",
                        "Size of the coherent domain along the second basis vector", 20000.0,
                        "size2");
    m_pdf1.initWithArgs("PDF 1", "Probability distribution in first lattice direction",
                        Profile2DItemCatalog::Type::Cauchy);
    m_pdf2.initWithArgs("PDF 2", "Probability distribution in second lattice direction",
                        Profile2DItemCatalog::Type::Cauchy);
}

std::unique_ptr<IInterference> Interference2DParacrystalItem::createInterference() const
{
    Lattice2DItem* latticeItem = latticeTypeItem();

    std::unique_ptr<Interference2DParacrystal> result(
        new Interference2DParacrystal(*latticeItem->createLattice(), 0, 0, 0));

    result->setDampingLength(m_damping_length);
    result->setDomainSizes(m_domain_size1, m_domain_size2);
    result->setIntegrationOverXi(xiIntegration());
    result->setProbabilityDistributions(*m_pdf1->createProfile(), *m_pdf2->createProfile());
    result->setPositionVariance(m_position_variance);
    return std::unique_ptr<IInterference>(result.release());
}

void Interference2DParacrystalItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    Interference2DAbstractLatticeItem::writeTo(w);
    w->writeEndElement();

    // damping length
    w->writeStartElement(Tag::DampingLength);
    m_damping_length.writeTo(w);
    w->writeEndElement();

    // domain size 1
    w->writeStartElement(Tag::DomainSize1);
    m_domain_size1.writeTo(w);
    w->writeEndElement();

    // domain size 2
    w->writeStartElement(Tag::DomainSize2);
    m_domain_size2.writeTo(w);
    w->writeEndElement();

    // pdf 1
    w->writeStartElement(Tag::PDF1);
    m_pdf1.writeTo(w);
    w->writeEndElement();

    // pdf 2
    w->writeStartElement(Tag::PDF2);
    m_pdf2.writeTo(w);
    w->writeEndElement();
}

void Interference2DParacrystalItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            Interference2DAbstractLatticeItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // damping length
        } else if (tag == Tag::DampingLength) {
            m_damping_length.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // domain size 1
        } else if (tag == Tag::DomainSize1) {
            m_domain_size1.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // domain size 2
        } else if (tag == Tag::DomainSize2) {
            m_domain_size2.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // pdf 1
        } else if (tag == Tag::PDF1) {
            m_pdf1.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // pdf 2
        } else if (tag == Tag::PDF2) {
            m_pdf2.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

InterferenceFinite2DLatticeItem::InterferenceFinite2DLatticeItem()
    : Interference2DAbstractLatticeItem(false)
{
}

std::unique_ptr<IInterference> InterferenceFinite2DLatticeItem::createInterference() const
{
    Lattice2DItem* latticeItem = latticeTypeItem();
    auto result = std::make_unique<InterferenceFinite2DLattice>(*latticeItem->createLattice(),
                                                                m_domain_size1, m_domain_size2);

    result->setIntegrationOverXi(xiIntegration());
    result->setPositionVariance(m_position_variance);

    return result;
}

void InterferenceFinite2DLatticeItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    Interference2DAbstractLatticeItem::writeTo(w);
    w->writeEndElement();

    // domain size 1
    w->writeStartElement(Tag::DomainSize1);
    XML::writeAttribute(w, XML::Attrib::value, m_domain_size1);
    w->writeEndElement();

    // domain size 2
    w->writeStartElement(Tag::DomainSize2);
    XML::writeAttribute(w, XML::Attrib::value, m_domain_size2);
    w->writeEndElement();
}

void InterferenceFinite2DLatticeItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            Interference2DAbstractLatticeItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // domain size 1
        } else if (tag == Tag::DomainSize1) {
            XML::readAttribute(r, XML::Attrib::value, &m_domain_size1);
            XML::gotoEndElementOfTag(r, tag);

            // domain size 2
        } else if (tag == Tag::DomainSize2) {
            XML::readAttribute(r, XML::Attrib::value, &m_domain_size2);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

InterferenceHardDiskItem::InterferenceHardDiskItem()
{
    m_radius.init("Radius (nm)", "Hard disk radius", 5.0, "radius");
    m_density.init("Total particle density (nm^-2)", "Particle density in particles per area",
                   0.002, 6, 0.0001 /* step */, RealLimits::nonnegative(), "density");
}

std::unique_ptr<IInterference> InterferenceHardDiskItem::createInterference() const
{
    auto result = std::make_unique<InterferenceHardDisk>(m_radius, m_density);
    result->setPositionVariance(m_position_variance);
    return std::unique_ptr<IInterference>(result.release());
}

void InterferenceHardDiskItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    InterferenceItem::writeTo(w);
    w->writeEndElement();

    // radius
    w->writeStartElement(Tag::Radius);
    m_radius.writeTo(w);
    w->writeEndElement();

    // density
    w->writeStartElement(Tag::Density);
    m_density.writeTo(w);
    w->writeEndElement();
}

void InterferenceHardDiskItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            InterferenceItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // radius
        } else if (tag == Tag::Radius) {
            m_radius.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // density
        } else if (tag == Tag::Density) {
            m_density.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}

// --------------------------------------------------------------------------------------------- //

InterferenceRadialParacrystalItem::InterferenceRadialParacrystalItem()
{
    m_peak_distance.init("Peak distance (nm)", "Average distance to the next neighbor", 20.0,
                         "peak");
    m_damping_length.init("Damping length (nm)",
                          "The damping (coherence) length of the paracrystal", 1000.0,
                          "dampingLen");
    m_domain_size.init("Domain size (nm)", "Size of coherence domain along the lattice main axis",
                       0.0, "size");
    m_kappa.init("SizeSpaceCoupling",
                 "Size spacing coupling parameter of the Size Spacing Correlation Approximation",
                 0.0, "kappa");
    m_pdf.initWithArgs("PDF", "One-dimensional probability distribution",
                       Profile1DItemCatalog::Type::Cauchy);
}

std::unique_ptr<IInterference> InterferenceRadialParacrystalItem::createInterference() const
{
    auto result =
        std::make_unique<InterferenceRadialParacrystal>(m_peak_distance, m_damping_length);
    result->setDomainSize(m_domain_size);
    result->setKappa(m_kappa);
    auto pdf = m_pdf->createProfile();
    result->setProbabilityDistribution(*pdf);
    result->setPositionVariance(m_position_variance);
    return std::unique_ptr<IInterference>(result.release());
}

void InterferenceRadialParacrystalItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    InterferenceItem::writeTo(w);
    w->writeEndElement();

    // peak distance
    w->writeStartElement(Tag::PeakDistance);
    m_peak_distance.writeTo(w);
    w->writeEndElement();

    // damping length
    w->writeStartElement(Tag::DampingLength);
    m_damping_length.writeTo(w);
    w->writeEndElement();

    // domain size
    w->writeStartElement(Tag::DomainSize);
    m_domain_size.writeTo(w);
    w->writeEndElement();

    // kappa
    w->writeStartElement(Tag::Kappa);
    m_kappa.writeTo(w);
    w->writeEndElement();

    // pdf
    w->writeStartElement(Tag::PDF);
    m_pdf.writeTo(w);
    w->writeEndElement();
}

void InterferenceRadialParacrystalItem::readFrom(QXmlStreamReader* r)
{
    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // parameters from base class
        if (tag == Tag::BaseData) {
            InterferenceItem::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // peak distance
        } else if (tag == Tag::PeakDistance) {
            m_peak_distance.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // damping length
        } else if (tag == Tag::DampingLength) {
            m_damping_length.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // domain size
        } else if (tag == Tag::DomainSize) {
            m_domain_size.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // kappa
        } else if (tag == Tag::Kappa) {
            m_kappa.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // pdf
        } else if (tag == Tag::PDF) {
            m_pdf.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
