//  ************************************************************************************************
//
//  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_, bool in_bins_);
    MaskPattern(const MaskPattern&) = delete;
    ~MaskPattern();
    MaskPattern* clone() const;
    IShape2D* shape; // cloneable
    bool doMask;
    bool inBins;
};

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

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

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


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, bool in_bins)
{
    m_stack.push_back(new MaskPattern(shape.clone(), mask_value, in_bins));
}

bool MaskStack::isMasked(size_t i_flat, const Frame& frame) const
{
    size_t nx = frame.projectedSize(0);
    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 = pat->inBins ? Bin1D::FromTo(ix - 0.5, ix + 0.5) : frame.xAxis().bin(ix);
        Bin1D biny = pat->inBins ? Bin1D::FromTo(iy - 0.5, iy + 0.5) : 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};
}
