//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Beam/Beam.cpp
//! @brief     Implements class Beam.
//!
//! @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 "Device/Beam/Beam.h"
#include "Base/Const/PhysicalConstants.h"
#include "Base/Spin/SpinMatrix.h"
#include "Base/Util/Assert.h"
#include "Base/Vector/GisasDirection.h"
#include "Device/Beam/IFootprint.h"

using PhysConsts::pi;

//... Constructors, destructors:

Beam::Beam(double intensity, double wavelength, double alpha, double phi)
    : m_intensity(intensity)
    , m_wavelength(wavelength)
    , m_alpha(alpha)
    , m_phi(phi)
{
    precompute();
}

Beam::~Beam() = default;

Beam* Beam::clone() const
{
    auto* result = new Beam(m_intensity, m_wavelength, m_alpha, m_phi);
    result->m_footprint = m_footprint;
    result->m_polarization = m_polarization;
    return result;
}

//... Getters:

std::vector<const INode*> Beam::nodeChildren() const
{
    if (m_footprint)
        return {m_footprint.get()};
    return {};
}

SpinMatrix Beam::polMatrix() const
{
    return SpinMatrix::FromBlochVector(m_polarization);
}

//... Setters:

void Beam::setIntensity(double intensity)
{
    m_intensity = intensity;
    precompute();
}

void Beam::setWavelength(double wavelength)
{
    if (wavelength <= 0)
        throw std::runtime_error("Wavelength = " + std::to_string(wavelength)
                                 + " : wavelength must be set to positive value");

    m_wavelength = wavelength;
    precompute();
}

void Beam::setInclination(const double alpha)
{
    m_alpha = alpha;
    precompute();
}

void Beam::setAzimuthalAngle(double value)
{
    m_phi = value;
    precompute();
}

void Beam::setFootprint(const IFootprint* shape_factor)
{
    m_footprint.reset(shape_factor ? shape_factor->clone() : nullptr);
}

//! Sets the polarization density matrix according to the given Bloch vector
void Beam::setPolarization(const R3& polarization)
{
    if (polarization.mag() > 1.0)
        throw std::runtime_error(
            "Beam::setPolarization: "
            "The given Bloch vector cannot represent a real physical ensemble");
    m_polarization = polarization;
}

//... Private function:

//! To be called whenever wavelength or alpha or phi has changed.
void Beam::precompute()
{
    ASSERT(m_intensity >= 0);
    ASSERT(m_wavelength >= 0);
    ASSERT(m_alpha >= 0);
    m_wavenumber = (2 * pi) / m_wavelength;
    m_k = vecOfKAlphaPhi(m_wavenumber, -m_alpha, -m_phi);
}
