#include "selectionmanager.h"
#include "classicmocknote.h"
#include "mockelement.h"
#include "graphics/classicselectiongraphics.h"
#include <algorithm>

SelectionManager::SelectionManager() :
    _multiselection_enabled(false)
{}

void SelectionManager::discard()
{
    for (const auto& note : _selected_notes)
        for (auto& element : note->getElements())
            element.selected = false;

    _selected_notes.clear();
}

void SelectionManager::fetch(ClassicMockNote * const note)
{
    bool already_there = std::any_of(_selected_notes.begin(), _selected_notes.end(),
                                     [&note](const auto& selected_note)
                                     {
                                         return note == selected_note;
                                     });

    if (!already_there)
        _selected_notes.emplace_back(note);
}

void SelectionManager::remove(ClassicMockNote * const note)
{
    for (std::size_t i = 0; i < _selected_notes.size(); ++i)
    {
        if (note == _selected_notes.at(i))
        {
            _selected_notes[i] = std::move(_selected_notes.back());
            _selected_notes.pop_back();
            break;
        }
    }
}

void SelectionManager::enableMultiselection(bool enable)
{
    _multiselection_enabled = enable;
}

bool SelectionManager::isMultiselectionEnabled() const
{
    return _multiselection_enabled;
}

void SelectionManager::display() const
{
    for (const auto& note : _selected_notes)
        for (const auto& element : note->getElements())
            if (element.selected)
            {
                element.selection->display();
            }
}
