//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Multilayer/LayerStack.h
//! @brief     Implements class LayerStack.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2024
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Sample/Multilayer/LayerStack.h"
#include "Base/Util/Assert.h"
#include "Base/Util/StringUtil.h"

LayerStack::LayerStack(size_t numRepetitions)
    : m_n_periods(numRepetitions)
{
    validateOrThrow();
}

LayerStack::~LayerStack() = default;

void LayerStack::addComponent(const ILayer& component)
{
    m_components.push_back(component.clone());
}

void LayerStack::addLayer(const Layer& layer)
{
    addComponent(layer);
}

void LayerStack::addStack(const LayerStack& substack)
{
    addComponent(substack);
}

LayerStack* LayerStack::clone() const
{
    auto* result = new LayerStack(m_n_periods);
    for (size_t i = 0; i < m_components.size(); ++i)
        result->addComponent(std::as_const(*m_components[i]));
    return result;
}

std::vector<const INode*> LayerStack::nodeChildren() const
{
    std::vector<const INode*> result;
    const size_t N = m_components.size();
    result.reserve(N);
    for (size_t i = 0; i < N; ++i)
        result.push_back(m_components.at(i));
    return result;
}

std::string LayerStack::validate() const
{
    std::vector<std::string> errs;
    for (size_t i = 0; i < m_components.size(); ++i) {
        std::string err = m_components[i]->validate();
        if (!err.empty())
            errs.push_back("{ component " + std::to_string(i) + ": " + err + " }");
    }

    if (!errs.empty())
        return "[ " + Base::String::join(errs, ", ") + " ]";

    m_validated = true;
    return "";
}

std::vector<const Layer*> LayerStack::unwrapped() const
{
    std::vector<const Layer*> unwrapped;
    for (const ILayer* component : m_components) {
        std::vector<const Layer*> unwrappedComponent = component->unwrapped();
        unwrapped.insert(unwrapped.end(), unwrappedComponent.begin(), unwrappedComponent.end());
    }
    std::vector<const Layer*> result;
    for (size_t i = 0; i < m_n_periods; i++)
        result.insert(result.end(), unwrapped.begin(), unwrapped.end());
    return result;
}

void LayerStack::checkMaterials(double wavelength) const
{
    for (const ILayer* component : m_components)
        component->checkMaterials(wavelength);
}
