//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sim/Computation/DWBAComputation.cpp
//! @brief     Implements class DWBAComputation.
//!
//! @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/DWBAComputation.h"
#include "Resample/Element/DiffuseElement.h"
#include "Resample/Flux/IFlux.h"
#include "Resample/Interparticle/IInterparticleStrategy.h"
#include "Resample/Option/SimulationOptions.h"
#include "Resample/Processed/ReLayout.h"
#include "Resample/Processed/ReSample.h"
#include "Sim/Computation/GISASSpecularContribution.h"
#include "Sim/Computation/RoughMultiLayerContribution.h"

namespace {

double dwbaContribution(const ReLayout& relayout, const DiffuseElement& ele)
{
    return relayout.interparticle_strategy()->evaluate(ele) * relayout.surfaceDensity();
}

} // namespace


// The normalization of the calculated scattering intensities is:
// For nanoparticles: rho * (scattering cross-section/scattering particle)
// For roughness: (scattering cross-section of area S)/S
// For specular peak: |R|^2 * sin(alpha_i) / solid_angle
// This allows them to be added and normalized together to the beam afterwards
double Compute::scattered_and_reflected(const ReSample& re_sample, const SimulationOptions& options,
                                        DiffuseElement& ele)
{
    const Fluxes fluxes_in = re_sample.fluxesIn(ele.getKi());
    const Fluxes fluxes_out = re_sample.fluxesOut(ele.meanKf());
    ele.setFluxes(&fluxes_in, &fluxes_out);

    double intensity = 0;
    for (const ReLayout* relayout : re_sample.relayouts())
        intensity += ::dwbaContribution(*relayout, ele);

    if (re_sample.hasRoughness())
        intensity += Compute::roughMultiLayerContribution(re_sample, ele);

    if (options.includeSpecular() && ele.isSpecular() && ele.solidAngle() > 0)
        intensity = Compute::gisasSpecularContribution(re_sample, ele);

    return intensity;
}
