//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/HardParticle/EllipsoidalCylinder.cpp
//! @brief     Implements class EllipsoidalCylinder.
//!
//! @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/HardParticle/EllipsoidalCylinder.h"
#include "Base/Math/Bessel.h"
#include "Base/Math/Functions.h"
#include "Base/Util/Assert.h"
#include "Sample/Shape/DoubleEllipse.h"
#include <numbers>

using std::numbers::pi;

EllipsoidalCylinder::EllipsoidalCylinder(double radius_x, double radius_y, double height)
    : HardFormfactor()
    , m_radius_x(radius_x)
    , m_radius_y(radius_y)
    , m_height(height)
{
    EllipsoidalCylinder::validate();
}

complex_t EllipsoidalCylinder::formfactorAtBottom(C3 q) const
{
    ASSERT(m_validated);
    complex_t qxRa = q.x() * m_radius_x;
    complex_t qyRb = q.y() * m_radius_y;
    complex_t qzHdiv2 = m_height / 2 * q.z();

    complex_t Fz = exp_I(qzHdiv2) * Math::sinc(qzHdiv2);
    complex_t gamma = std::sqrt((qxRa) * (qxRa) + (qyRb) * (qyRb));
    complex_t J1_gamma_div_gamma = Math::Bessel::J1c(gamma);

    return (2 * pi) * m_radius_x * m_radius_y * m_height * Fz * J1_gamma_div_gamma;
}

void EllipsoidalCylinder::validate() const
{
    if (m_radius_x <= 0)
        throw std::runtime_error("radius_x <= 0");
    if (m_radius_y <= 0)
        throw std::runtime_error("radius_y <= 0");
    if (m_height <= 0)
        throw std::runtime_error("height <= 0");

    m_shape3D =
        std::make_unique<DoubleEllipseZ>(m_radius_x, m_radius_y, m_height, m_radius_x, m_radius_y);

    m_validated = true;
}

double EllipsoidalCylinder::radialExtension() const
{
    ASSERT(m_validated);
    return (m_radius_x + m_radius_y) / 2.0;
}

bool EllipsoidalCylinder::contains(const R3& position) const
{
    double a = radiusX(); // semi-axis length along x
    double b = radiusY(); // semi-axis length along y
    double H = height();

    if (std::abs(position.x()) > a || std::abs(position.y()) > b || position.z() < 0
        || position.z() > H)
        return false;

    if (std::pow(position.x() / a, 2) + std::pow(position.y() / b, 2) <= 1)
        return true;

    return false;
}
