//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Particle/IFormFactor.cpp
//! @brief     Implements class interface IFormFactor.
//!
//! @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/Particle/IFormFactor.h"
#include "Base/Py/PyFmt.h"
#include "Base/Type/Span.h"
#include "Base/Util/Assert.h"
#include "Base/Util/StringUtil.h"
#include "Base/Vector/WavevectorInfo.h"
#include "Sample/Particle/PolyhedralUtil.h"
#include "Sample/Scattering/Rotations.h"
#include "Sample/Shape/IShape3D.h"
#include <sstream>
#include <stdexcept>

IFormFactor::IFormFactor() = default;

IFormFactor::IFormFactor(const std::vector<double>& PValues)
    : ISampleNode(PValues)
{
}

IFormFactor::~IFormFactor() = default;

double IFormFactor::volume() const
{
    return std::abs(formfactor(C3()));
}

Span IFormFactor::spanZ(const IRotation* rotation) const
{
    ASSERT(m_shape3D);
    return PolyhedralUtil::spanZ(m_shape3D->vertices(), rotation);
}

bool IFormFactor::canSliceAnalytically(const IRotation* rotation) const
{
    return !rotation || rotation->zInvariant();
}

std::string IFormFactor::pythonConstructor() const
{
    std::vector<std::pair<double, std::string>> arguments;
    for (size_t i = 0; i < parDefs().size(); i++)
        arguments.emplace_back(m_P[i], parDefs()[i].unit);

    return Py::Fmt::printFunction(className(), arguments);
}

complex_t IFormFactor::theFF(const WavevectorInfo& wavevectors) const
{
    const complex_t result = formfactor(wavevectors.getQ());
    if (!std::isfinite(result.real()) || !std::isfinite(result.imag())) {
        std::stringstream msg;
        msg << "Infinite form factor " << result << " at ki " << wavevectors.getKi() << " kf "
            << wavevectors.getKf() << " q " << wavevectors.getQ();
        throw std::runtime_error(msg.str());
    }
    return result;
}

SpinMatrix IFormFactor::thePolFF(const WavevectorInfo& wavevectors) const
{
    return formfactor_pol(wavevectors.getQ());
}

SpinMatrix IFormFactor::formfactor_pol(C3 q) const
{
    return formfactor(q) * SpinMatrix::One();
}

bool IFormFactor::isEqualTo(const IFormFactor* other) const
{
    ASSERT(!className().empty());
    ASSERT(!other->className().empty());
    return className() == other->className() && pars() == other->pars();
}
