//  ************************************************************************************************
//
//  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();
}
