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

using std::numbers::pi;

Spheroid::Spheroid(double radius_xy, double radius_z)
    : HardFormfactor()
    , m_radius_xy(radius_xy)
    , m_radius_z(radius_z)
{
    Spheroid::validate();
    m_shape3D = std::make_unique<TruncatedEllipsoidNet>(m_radius_xy, m_radius_xy, m_radius_z,
                                                        2 * m_radius_z, 0.0);
}

complex_t Spheroid::formfactorAtBottom(C3 q) const
{
    ASSERT(m_validated);
    double Rz = m_radius_z;
    double Rxy = m_radius_xy;

    // complex length of q (not a sesquilinear dot product!),
    // xy components multiplied with R, z component multiplied with h
    complex_t qR = sqrt(Rxy * Rxy * (q.x() * q.x() + q.y() * q.y()) + Rz * Rz * q.z() * q.z());

    complex_t zFactor = exp_I(Rz * q.z());

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

    return 4 * pi / pow(qR, 3) * Rxy * Rxy * Rz * (sin(qR) - qR * cos(qR)) * zFactor;
}

void Spheroid::validate() const
{
    if (m_radius_xy <= 0)
        throw std::runtime_error("radius_xy <= 0");
    if (m_radius_z <= 0)
        throw std::runtime_error("radius_z <= 0");
    m_validated = true;
}

bool Spheroid::contains(const R3& position) const
{
    double rxy = radiusXY(); // semi-axis length along x and y
    double rz = radiusZ();   // semi-axis length along z
    double H = 2 * rz;

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

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

    return false;
}
