//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/HardParticle/Sphere.cpp
//! @brief     Implements class Sphere.
//!
//! @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/Sphere.h"
#include "Base/Util/Assert.h"
#include "Sample/LibFF/SomeFormfactor.h"
#include "Sample/Particle/Rotations.h"

Sphere::Sphere(double radius)
    : HardFormfactor()
    , m_radius(radius)
{
    Sphere::validate();
}

complex_t Sphere::formfactorAtBottom(C3 q) const
{
    ASSERT(m_validated);
    complex_t result = SampleUtil::someff::ffSphere(q, m_radius);
    result *= exp_I(q.z() * m_radius); // shift from center to bottom
    return result;
}

void Sphere::validate() const
{
    if (m_radius <= 0)
        throw std::runtime_error("radius <= 0");

    m_validated = true;
}

double Sphere::zBottom(const Rotation* rotation) const
{
    if (!rotation)
        return 0;
    R3 centre(0.0, 0.0, m_radius);
    return rotation->transformed(centre).z() - m_radius;
}

double Sphere::zTop(const Rotation* rotation) const
{
    if (!rotation)
        return 2 * m_radius;
    R3 centre(0.0, 0.0, m_radius);
    return rotation->transformed(centre).z() + m_radius;
}

bool Sphere::contains(const R3& position) const
{
    double R = radius();

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

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

    return false;
}
