//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Resample/Element/DiffuseElement.cpp
//! @brief     Implements class DiffuseElement.
//!
//! @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 "Resample/Element/DiffuseElement.h"
#include "Base/Axis/Pixel.h"
#include "Base/Const/PhysicalConstants.h"
#include "Base/Vector/GisasDirection.h"
#include "Base/Vector/WavevectorInfo.h"
#include "Resample/Flux/IFlux.h"

using PhysConsts::pi;

DiffuseElement::DiffuseElement(double wavelength, double alpha_i, double phi_i,
                               const Pixel* const pixel, const SpinMatrix& polarizer,
                               const SpinMatrix& analyzer, bool isSpecular_,
                               const Fluxes* const fluxes_in, const Fluxes* const fluxes_out)
    : IElement({polarizer, analyzer})
    , m_wavelength(wavelength)
    , m_alpha_i(alpha_i)
    , m_phi_i(phi_i)
    , m_k_i(vecOfLambdaAlphaPhi(m_wavelength, -m_alpha_i, -m_phi_i))
    , m_mean_kf(pixel->getK(0.5, 0.5, m_wavelength))
    , m_pixel(pixel)
    , m_is_specular(isSpecular_)
    , m_fluxes_in(fluxes_in)
    , m_fluxes_out(fluxes_out)
{
}

void DiffuseElement::setFluxes(const Fluxes* fluxes_in, const Fluxes* fluxes_out)
{
    m_fluxes_in = fluxes_in;
    m_fluxes_out = fluxes_out;
}

const IFlux* DiffuseElement::fluxIn(size_t i_layer) const
{
    return (*m_fluxes_in)[i_layer];
}

const IFlux* DiffuseElement::fluxOut(size_t i_layer) const
{
    return (*m_fluxes_out)[i_layer];
}

DiffuseElement DiffuseElement::pointElement(double x, double y) const
{
    return {m_wavelength,  m_alpha_i,
            m_phi_i,       m_pixel->createZeroSizePixel(x, y), // TODO simplify
            polarizer(),   analyzer(),
            m_is_specular, m_fluxes_in,
            m_fluxes_out};
} //! Returns outgoing wavevector Kf for in-pixel coordinates x,y.
//! In-pixel coordinates take values from 0 to 1.
R3 DiffuseElement::getKf(double x, double y) const
{
    return m_pixel->getK(x, y, m_wavelength);
}

R3 DiffuseElement::meanQ() const
{
    return getKi() - meanKf();
}

double DiffuseElement::alpha(double x, double y) const
{
    return (pi / 2) - R3Util::theta(getKf(x, y));
}

WavevectorInfo DiffuseElement::wavevectorInfo() const
{
    return {getKi(), meanKf(), wavelength()};
}

double DiffuseElement::integrationFactor(double x, double y) const
{
    return m_pixel->integrationFactor(x, y);
}

double DiffuseElement::solidAngle() const
{
    return m_pixel->solidAngle();
}
