//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sim/Evaluate/EvaluateSpecularGisas.cpp
//! @brief     Implements function Evaluate::gisasSpecularContribution.
//!
//! @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 "Sim/Evaluate/EvaluateSpecularGisas.h"
#include "Base/Util/Assert.h"
#include "Resample/Sample/ReSample.h"
#include "Sample/Element/DiffuseElement.h"
#include "Sample/Flux/MatrixFlux.h"
#include "Sample/Flux/ScalarFlux.h"
#include "Sim/Evaluate/EvaluateSpecular.h"

double Evaluate::gisasSpecularContribution(const ReSample& re_sample, DiffuseElement& ele,
                                           bool polarized)
{
    double sin_alpha_i = std::abs(std::sin(ele.alphaI()));
    if (sin_alpha_i == 0.0)
        return 0;

    const double solid_angle = ele.solidAngle();
    if (solid_angle <= 0.0)
        return 0;

    const Fluxes fluxes_in = re_sample.fluxesIn(ele.getKi(), polarized);
    ele.setFluxes(&fluxes_in, nullptr);

    double geom_factor = sin_alpha_i / solid_angle;

    if (polarized) {
        const auto* flux = dynamic_cast<const MatrixFlux*>(ele.fluxIn(0));
        ASSERT(flux);

        const SpinMatrix R = flux->reflectionMatrix();
        const SpinMatrix& polMatrix = ele.polarizer();
        const SpinMatrix& anaMatrix = ele.analyzer();

        return Evaluate::magneticR(R, polMatrix, anaMatrix) * geom_factor;
    }

    const auto* flux = dynamic_cast<const ScalarFlux*>(ele.fluxIn(0));
    ASSERT(flux);

    const complex_t R = flux->getScalarR();
    return Evaluate::scalarR(R) * geom_factor;
}
