#include <layer_stack.hpp>

namespace OpenEngine {
    LayerStack::LayerStack()
    {
    }

    LayerStack::~LayerStack()
    {
        for (Layer* layer : layers)
            delete layer;
    }

    void LayerStack::PushLayer(Layer* layer)
    {
        layers.emplace(layers.begin() + layer_insert_index, layer);
        layer_insert_index++;
        layer->OnAttach();
    }

    void LayerStack::PushOverlay(Layer* overlay)
    {
        layers.emplace_back(overlay);
        overlay->OnAttach();
    }

    void LayerStack::PopLayer(Layer* layer)
    {
        auto it = std::find(layers.begin(), layers.begin() + layer_insert_index, layer);
        if (it != layers.end()) {
            layer->OnDetach();
            layers.erase(it);
            layer_insert_index--;
        }
    }

    void LayerStack::PopOverlay(Layer* overlay)
    {
        auto it = std::find(layers.begin() + layer_insert_index, layers.end(), overlay);
        if (it != layers.end()) {
            overlay->OnDetach();
            layers.erase(it);
        }
    }
}
