//  ************************************************************************************************
//
//  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/Frame.h"
#include "Base/Axis/Scale.h"
#include "Device/Data/Datafield.h"
#include "Device/Mask/IShape2D.h"

struct MaskPattern {
    MaskPattern(IShape2D* shape_, bool doMask_);
    MaskPattern(const MaskPattern&) = delete;
    ~MaskPattern();
    MaskPattern* clone() const;
    IShape2D* shape; // cloneable
    bool doMask;
};

MaskPattern::MaskPattern(IShape2D* shape_, bool doMask_)
    : shape(shape_)
    , doMask(doMask_)
{
}

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

MaskPattern* MaskPattern::clone() const
{
    return new MaskPattern(shape->clone(), doMask);
}


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

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

void MaskStack::pushMask(const IShape2D& shape, bool mask_value)
{
    m_stack.push_back(new MaskPattern(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 MaskPattern* const 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<IShape2D*, bool> MaskStack::patternAt(size_t iMask) const
{
    const MaskPattern* pat = m_stack.at(iMask);
    return {pat->shape, pat->doMask};
}
