//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Mask/MaskStack.cpp
//! @brief     Implements class MaskStack.
//!
//! @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/Mask/MaskStack.h"
#include "Base/Axis/Bin.h"
#include "Base/Axis/Frame.h"
#include "Base/Axis/Scale.h"
#include "Device/Data/Datafield.h"
#include "Device/Mask/Shape2D.h"

struct ShapeWrapper {
    ShapeWrapper(Shape2D* shape_, bool doMask_);
    ShapeWrapper(const ShapeWrapper&) = delete;
    ~ShapeWrapper();
    std::unique_ptr<ShapeWrapper> clone() const;
    Shape2D* shape; // cloneable
    bool doMask;
};

ShapeWrapper::ShapeWrapper(Shape2D* shape_, bool doMask_)
    : shape(shape_)
    , doMask(doMask_)
{
}

ShapeWrapper::~ShapeWrapper()
{
    delete shape;
}

std::unique_ptr<ShapeWrapper> ShapeWrapper::clone() const
{
    return std::make_unique<ShapeWrapper>(shape->clone(), doMask);
}


MaskStack::MaskStack() = default;
MaskStack::~MaskStack() = default;

MaskStack* MaskStack::clone() const
{
    auto* result = new MaskStack;
    for (const auto& p : m_stack)
        result->m_stack.push_back({p->clone()});
    return result;
}

void MaskStack::pushMask(const Shape2D& shape, bool mask_value)
{
    m_stack.push_back(std::make_unique<ShapeWrapper>(shape.clone(), mask_value));
}

bool MaskStack::isMasked(size_t i_flat, const Frame& frame) const
{
    size_t nx = frame.xAxis().size();
    size_t ix = i_flat % nx;
    size_t iy = i_flat / nx;

    for (int k = m_stack.size() - 1; k >= 0; --k) {
        const auto& pat = m_stack[k];
        Bin1D binx = frame.xAxis().bin(ix);
        Bin1D biny = frame.yAxis().bin(iy);
        if (pat->shape->contains(binx, biny))
            return pat->doMask;
    }
    return false;
}

bool MaskStack::hasMasks() const
{
    return !m_stack.empty();
}

size_t MaskStack::numberOfMasks() const
{
    return m_stack.size();
}

std::pair<Shape2D*, bool> MaskStack::patternAt(size_t iMask) const
{
    const auto& pat = m_stack.at(iMask);
    return {pat->shape, pat->doMask};
}
