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

using PhysConsts::pi;

GaussSphere::GaussSphere(const std::vector<double> P)
    : IFormfactor(P)
    , m_mean_radius(m_P[0])
{
    validateOrThrow();
}

GaussSphere::GaussSphere(double mean_radius)
    : GaussSphere(std::vector<double>{mean_radius})
{
}

complex_t GaussSphere::formfactor(C3 q) const
{
    ASSERT(m_validated);
    const double max_ql = std::sqrt(-4 * pi * std::log(std::numeric_limits<double>::min()) / 3);

    double qzh = q.z().real() * m_mean_radius;
    if (std::abs(qzh) > max_ql)
        return 0.0;
    double qxr = q.x().real() * m_mean_radius;
    if (std::abs(qxr) > max_ql)
        return 0.0;
    double qyr = q.y().real() * m_mean_radius;
    if (std::abs(qyr) > max_ql)
        return 0.0;

    return pow(m_mean_radius, 3) * std::exp(-(qxr * qxr + qyr * qyr + qzh * qzh) / 4.0 / pi);
}

std::string GaussSphere::validate() const
{
    std::vector<std::string> errs;
    requestGt0(errs, m_mean_radius, "mean_radius");
    if (!errs.empty())
        return jointError(errs);

    const double R = m_mean_radius;
    m_shape3D = std::make_unique<TruncatedEllipsoidNet>(R, R, R, 2 * R, 0);

    m_validated = true;
    return "";
}

bool GaussSphere::contains(const R3&) const
{
    throw std::runtime_error("Soft particle cannot be used as mesocrystal outer shape");
}
