//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Resample/Slice/Slice.cpp
//! @brief     Implements class Slice.
//!
//! @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/Slice/Slice.h"
#include "Base/Spin/SpinMatrix.h"
#include "Resample/Slice/SliceStack.h"
#include "Sample/Interface/LayerRoughness.h"
#include "Sample/Material/MaterialUtil.h"
#include <numbers>
#include <utility>

using std::numbers::pi;

Slice::Slice(const ZLimits& zRange, Material material, const R3& B_field,
             const LayerRoughness* const roughness)
    : m_z_range(zRange)
    , m_material(std::move(material))
    , m_B_field(B_field)
    , m_top_roughness(roughness)
{
}

Slice::~Slice() = default;

void Slice::setMaterial(const Material& material)
{
    m_material = material;
}

const Material& Slice::material() const
{
    return m_material;
}

double Slice::low() const
{
    return m_z_range.low();
}

double Slice::hig() const
{
    return m_z_range.hig();
}

double Slice::higOr0() const
{
    return m_z_range.higOr0();
}

double Slice::thicknessOr0() const
{
    return m_z_range.thicknessOr0();
}

const LayerRoughness* Slice::topRoughness() const
{
    return m_top_roughness;
}

complex_t Slice::scalarReducedPotential(R3 k, double n_ref) const
{
    complex_t n = m_material.refractiveIndex((2 * pi) / k.mag());
    return MaterialUtil::ScalarReducedPotential(n, k, n_ref);
}

// ISSUE #394 currently unused
SpinMatrix Slice::polarizedReducedPotential(R3 k, double n_ref) const
{
    complex_t n = m_material.refractiveIndex((2 * pi) / k.mag());
    return MaterialUtil::PolarizedReducedPotential(n, m_B_field, k, n_ref);
}

void Slice::initBField(R3 h_field, double h_z)
{
    // Temporary forbid z-magnetization in all layers (see issue #654)
    if (m_material.magnetization().z() != 0)
        throw std::runtime_error("Processing z-magnetization of layers is not implemented.");

    static constexpr double Magnetic_Permeability = 4e-7 * pi;
    m_B_field = Magnetic_Permeability * (h_field + m_material.magnetization());
    m_B_field.setZ(Magnetic_Permeability * h_z);
}

void Slice::invertBField()
{
    m_B_field = -m_B_field;
}
