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

using PhysConsts::pi;

HemiEllipsoid::HemiEllipsoid(const std::vector<double> P)
    : IFormfactor(P)
    , m_radius_x(m_P[0])
    , m_radius_y(m_P[1])
    , m_height(m_P[2])
{
    validateOrThrow();
}

HemiEllipsoid::HemiEllipsoid(double radius_x, double radius_y, double height)
    : HemiEllipsoid(std::vector<double>{radius_x, radius_y, height})
{
}

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

complex_t HemiEllipsoid::formfactor(C3 q) const
{
    ASSERT(m_validated);
    const double R = m_radius_x;
    const double W = m_radius_y;
    const double H = m_height;
    const complex_t G = std::sqrt((q.x() * R) * (q.x() * R) + (q.y() * W) * (q.y() * W));
    const complex_t HQ = q.z() * H;

    if (std::abs(q.mag()) <= std::numeric_limits<double>::epsilon())
        return (2 * pi) * R * W * H / 3.;

    return (2 * pi) * H * R * W
           * ComplexIntegrator().integrate(
               [=](double z) {
                   const double cz = 1 - z * z;
                   return cz * Math::Bessel::J1c(G * std::sqrt(cz)) * exp_I(HQ * z);
               },
               0., 1.);
}

std::string HemiEllipsoid::validate() const
{
    std::vector<std::string> errs;
    requestGt0(errs, m_radius_x, "radius_x");
    requestGt0(errs, m_radius_y, "radius_y");
    requestGt0(errs, m_height, "height");
    if (!errs.empty())
        return jointError(errs);

    m_shape3D =
        std::make_unique<TruncatedEllipsoidNet>(m_radius_x, m_radius_x, m_height, m_height, 0.0);

    m_validated = true;
    return "";
}

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

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

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

    return false;
}
