//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/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 "Sample/Element/DiffuseElement.h"
#include "Base/Axis/Pixel.h"
#include "Base/Vector/GisasDirection.h"
#include "Base/Vector/WavevectorInfo.h"
#include "Sample/Flux/Flux.h"
#include <numbers>

using std::numbers::pi;

DiffuseElement::DiffuseElement(double wavelength, double alpha_i, double phi_i,
                               const Pixel* const pixel, const SpinMatrix& polarizer,
                               const SpinMatrix& analyzer, const Fluxes* const fluxes_in,
                               const Fluxes* const fluxes_out)
    : Element({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_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 Flux* DiffuseElement::fluxIn(size_t i_slice) const
{
    return (*m_fluxes_in)[i_slice].get();
}

const Flux* DiffuseElement::fluxOut(size_t i_slice) const
{
    return (*m_fluxes_out)[i_slice].get();
}

DiffuseElement DiffuseElement::pointElement(double x, double y) const
{
    return {m_wavelength, m_alpha_i,  m_phi_i,     m_pixel->newZeroSizePixel(x, y), // TODO simplify
            polarizer(),  analyzer(), m_fluxes_in, m_fluxes_out};
}

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

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

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

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

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

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