//  ************************************************************************************************
//
//  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/Const/PhysicalConstants.h"
#include "Base/Math/Bessel.h"
#include "Base/Math/Functions.h"
#include "Base/Util/Assert.h"
#include "Sample/Shape/DoubleEllipse.h"

using PhysConsts::pi;

EllipsoidalCylinder::EllipsoidalCylinder(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();
}

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

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

complex_t EllipsoidalCylinder::formfactor(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;
}

std::string EllipsoidalCylinder::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<DoubleEllipseZ>(m_radius_x, m_radius_y, m_height, m_radius_x, m_radius_y);

    m_validated = true;
    return "";
}

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;
}
