//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Aggregate/ICrystal2D.cpp
//! @brief     Implements the interface class ICrystal2D.
//!
//! @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 "Sample/Aggregate/ICrystal2D.h"
#include "Base/Math/Integrator.h"
#include "Base/Util/Assert.h"
#include "Sample/Lattice/Lattice2D.h"
#include <numbers>

using std::numbers::pi;

ICrystal2D::ICrystal2D(const IParticle& particle, const Lattice2D& lattice)
    : Ordered2D(particle)
    , m_integrate_xi(false)
{
    m_lattice.reset(lattice.clone());
}

ICrystal2D::~ICrystal2D() = default;

void ICrystal2D::setIntegrationOverXi(bool integrate_xi)
{
    m_integrate_xi = integrate_xi;
    m_lattice->setRotationEnabled(!m_integrate_xi); // deregister Xi in the case of integration
}

const Lattice2D& ICrystal2D::lattice() const
{
    ASSERT(m_lattice);
    return *m_lattice;
}

double ICrystal2D::areaNumberDensity() const
{
    double area = m_lattice->unitCellArea();
    ASSERT(area);
    return 1.0 / area;
}

double ICrystal2D::iff_without_dw(const R3& q) const
{
    if (!m_integrate_xi)
        return interferenceForXi(m_lattice->rotationAngle(), q.x(), q.y());
    double range = pi;
    return RealIntegrator().integrate(
               [&](double xi) -> double { return interferenceForXi(xi, q.x(), q.y()); }, 0.0, range)
           / range;
}

void ICrystal2D::instructCrystalClone(ICrystal2D* dest) const
{
    // Does not call Ordered2D::instructClone! Do it in the target class!
    dest->setIntegrationOverXi(integrationOverXi());
}
