/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <vector>

template <class T>
class MvCommandHistory
{
public:
    MvCommandHistory() = default;

    void clear();
    bool canRedo();
    bool canUndo();
    const T& undo();
    const T& redo();
    void add(const T&);

protected:
    bool isPosCorrect();
    void removeAfterCurrent();
    bool isCurrentCorrect() { return isPosCorrect(); }

    T defaultItem_;
    std::vector<T> items_;
    int pos_{0};
};

template <class T>
void MvCommandHistory<T>::clear()
{
    items_.clear();
    pos_ = 0;
}

template <class T>
bool MvCommandHistory<T>::isPosCorrect()
{
    return (pos_ >= 0 && pos_ < static_cast<int>(items_.size()));
}

template <class T>
bool MvCommandHistory<T>::canRedo()
{
    return (pos_ >= 0 && pos_ <= static_cast<int>(items_.size()) - 1);
}

template <class T>
bool MvCommandHistory<T>::canUndo()
{
    return (pos_ > 0 && pos_ <= static_cast<int>(items_.size()));
}

template <class T>
const T& MvCommandHistory<T>::redo()
{
    if (canRedo()) {
        int actPos = pos_;
        pos_++;
        return items_[actPos];
    }
    else {
        return defaultItem_;
    }
}

template <class T>
const T& MvCommandHistory<T>::undo()
{
    if (canUndo()) {
        int actPos = pos_;
        pos_--;
        return items_[actPos - 1];
    }
    else {
        return defaultItem_;
    }
}

/*template <class T>
const T& MvCommandHistory<T>::current()
{
    return (isPosCorrect())?items_[pos_]:defaultItem_;
}*/

template <class T>
void MvCommandHistory<T>::add(const T& item)
{
    removeAfterCurrent();
    items_.push_back(item);
    pos_ = static_cast<int>(items_.size());
}

template <class T>
void MvCommandHistory<T>::removeAfterCurrent()
{
    if (isPosCorrect()) {
        while (static_cast<int>(items_.size()) > pos_) {
            items_.pop_back();
        }
    }
}
