//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Base/Type/VectorWC.h
//! @brief     Defines and implements templated class VectorWC.
//!
//! @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)
//
//  ************************************************************************************************

#ifdef SWIG
#error no need to expose this header to Swig
#endif // SWIG
#ifndef BORNAGAIN_BASE_TYPE_VECTORWC_H
#define BORNAGAIN_BASE_TYPE_VECTORWC_H

#include "Base/Type/OwningVector.h"
#include "Base/Util/Assert.h"

//! An OwningVector with a current index.

template <typename T> class VectorWC : public OwningVector<T> {
    using super = OwningVector<T>;

public:
    void push_back(T* e)
    {
        super::push_back(e);
        m_current_index = super::size() - 1;
    }
    void insert_at(size_t i, T* e)
    {
        super::insert_at(i, e);
        m_current_index = i;
    }
    void replace_at(size_t i, T* e)
    {
        super::replace_at(i, e);
        m_current_index = i;
    }
    void delete_element(const T* e)
    {
        super::delete_element(e);
        update_current();
    }
    void delete_at(size_t i)
    {
        super::delete_at(i);
        update_current();
    }
    void delete_current()
    {
        ASSERT(m_current_index != size_t(-1));
        super::delete_at(m_current_index);
        update_current();
    }
    void swap(size_t from, size_t to)
    {
        super::swap(from, to);
        // TODO update m_current_index ?
    }
    void clear()
    {
        super::clear();
        m_current_index = -1;
    }

    void setCurrentIndex(size_t i)
    {
        ASSERT(i < super::size() || i == size_t(-1));
        if (i != m_current_index)
            m_current_index = i;
    }
    size_t currentIndex() const { return m_current_index; }
    const T* currentItem() const
    {
        return m_current_index < super::size() ? super::at(m_current_index) : (T*)nullptr;
    }
    T* currentItem()
    {
        return m_current_index < super::size() ? super::at(m_current_index) : (T*)nullptr;
    }

private:
    void update_current()
    {
        if (m_current_index == super::size())
            m_current_index = super::size() - 1;
    }

    size_t m_current_index = -1;
};

#endif // BORNAGAIN_BASE_TYPE_VECTORWC_H
