//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Aggregate/FiniteCrystal2D.cpp
//! @brief     Implements class FiniteCrystal2D.
//!
//! @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/FiniteCrystal2D.h"
#include "Base/Math/Functions.h"

using Math::Laue;

//! Constructor of two-dimensional finite lattice interference function.
//! @param particle: particle (or Mixture) populating the lattice
//! @param lattice: object specifying a 2d lattice structure
//! @param N_1: number of lattice cells in the first lattice direction
//! @param N_2: number of lattice cells in the second lattice direction
FiniteCrystal2D::FiniteCrystal2D(const IParticle& particle, const Lattice2D& lattice, unsigned N_1,
                                 unsigned N_2)
    : Ordered2D(particle)
    , LongRangeOrdered2D(particle, 0)
    , ICrystal2D(particle, lattice)
    , m_N_1(N_1)
    , m_N_2(N_2)
{
}

FiniteCrystal2D::~FiniteCrystal2D() = default;

FiniteCrystal2D* FiniteCrystal2D::clone() const
{
    auto* result = new FiniteCrystal2D(*m_particle, *m_lattice, m_N_1, m_N_2);
    instructLRClone(result);
    instructCrystalClone(result);
    return result;
}

double FiniteCrystal2D::interferenceForXi(double xi, double qx, double qy) const
{
    double a = m_lattice->length1();
    double b = m_lattice->length2();
    double xialpha = xi + m_lattice->latticeAngle();

    double qadiv2 = (qx * a * std::cos(xi) + qy * a * std::sin(xi)) / 2.0;
    double qbdiv2 = (qx * b * std::cos(xialpha) + qy * b * std::sin(xialpha)) / 2.0;
    double ampl = Laue(qadiv2, m_N_1) * Laue(qbdiv2, m_N_2);
    double lattice_factor = ampl * ampl / (m_N_1 * m_N_2);

    return lattice_factor;
}
