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

using std::numbers::pi;

Ellipsoid::Ellipsoid(double radius_x, double radius_y, double radius_z)
    : HardFormfactor()
    , m_radius_x(radius_x)
    , m_radius_y(radius_y)
    , m_radius_z(radius_z)
{
    Ellipsoid::validate();
}

complex_t Ellipsoid::formfactorAtBottom(C3 q) const
{
    ASSERT(m_validated);
    const double Rx = m_radius_x;
    const double Ry = m_radius_y;
    const double Rz = m_radius_z;
    const complex_t s =
        std::sqrt(q.x() * q.x() * Rx * Rx + q.y() * q.y() * Ry * Ry + q.z() * q.z() * Rz * Rz);
    complex_t zFactor = exp_I(Rz * q.z());

    if (std::abs(s) < 1e-4)
        // expand sin(S)-S*cos(S) up to S^5
        return 4 * pi / 3 * Rx * Ry * Rz * (1. - 0.1 * pow(s, 2)) * zFactor;

    return 4 * pi / pow(s, 3) * Rx * Ry * Rz * (sin(s) - s * cos(s)) * zFactor;
}

void Ellipsoid::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_radius_z <= 0)
        throw std::runtime_error("radius_z <= 0");

    m_shape3D = std::make_unique<TruncatedEllipsoidNet>(m_radius_x, m_radius_y, m_radius_z,
                                                        2 * m_radius_z, 0.0);
    m_validated = true;
}

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

bool Ellipsoid::contains(const R3& position) const
{
    double Rx = radiusX(); // semi-axis length along x
    double Ry = radiusY(); // semi-axis length along y
    double Rz = radiusZ(); // semi-axis length along z

    if (std::abs(position.x()) > Rx || std::abs(position.y()) > Ry || position.z() > 2 * Rz
        || position.z() < 0)
        return false;

    if (std::pow(position.x() / Rx, 2) + std::pow(position.y() / Ry, 2)
            + std::pow((position.z() - Rz) / Rz, 2)
        <= 1)
        return true;

    return false;
}
