//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sim/Computation/GISASSpecularContribution.cpp
//! @brief     Implements class 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/Computation/GISASSpecularContribution.h"
#include "Base/Util/Assert.h"
#include "Resample/Element/DiffuseElement.h"
#include "Resample/Flux/MatrixFlux.h"
#include "Resample/Flux/ScalarFlux.h"
#include "Resample/Processed/ReSample.h"
#include "Sim/Computation/SpecularComputation.h"

double Compute::gisasSpecularContribution(const ReSample& re_sample, const DiffuseElement& ele)
{
    if (!ele.isSpecular())
        return 0;

    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;

    double geom_factor = sin_alpha_i / solid_angle;

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

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

        return Compute::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 Compute::scalarR(R) * geom_factor;
}
