//  ************************************************************************************************
//
//  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/Spin/SpinMatrix.h"
#include "Base/Util/Assert.h"
#include "Base/Vector/GisasDirection.h"
#include "Device/Beam/Footprint.h"
#include <numbers>

using std::numbers::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;

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

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;
}

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

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::setGrazingAngle(const double alpha)
{
    m_alpha = alpha;
    precompute();
}

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

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

void Beam::precompute()
{
    ASSERT(m_intensity >= 0);
    ASSERT(m_wavelength >= 0);
    // Alpha can be negative (beam from below) but must not be too close to zero (ill-defined
    // physics)
    ASSERT(std::abs(m_alpha) >= minGrazingAngle || m_alpha == 0);
    m_wavenumber = (2 * pi) / m_wavelength;
    m_k = vecOfKAlphaPhi(m_wavenumber, -m_alpha, m_phi);
}
