#include "classicmocknote.h"
#include "graphics/classicscenegraphicsmanager.h"
#include "graphics/animations/classicanimationscenario.h"
#include "editor/selectionmanager.h"

ClassicMockNote::ClassicMockNote(ArrowNoteInitializer&& init, const std::shared_ptr<SelectionManager<ClassicMockNote>>& selection_manager) :
    ClassicNote(std::move(init.initializer)),
    _selection_manager(selection_manager)
{
    _elements.resize(init.elements.size());

    for (std::size_t i = 0; i < _elements.size(); ++i)
    {
        _elements[i].position = init.elements[i].element.position;
        _elements[i].type = init.elements[i].element.type;
    }
}

bool ClassicMockNote::isActive(const kku::microsec &offset) const
{
    (void)offset;
    return _state != State::DEAD
        && _state != State::NONE;
}

void ClassicMockNote::input(kku::GameEvent&& input)
{
    switch (input.event.type)
    {

    default:
        break;

    case kku::SystemEvent::Type::MousePress:
    {
        bool selection_changed = false;
        std::size_t amount_selected = 0;

        const auto position = std::get<kku::SystemEvent::Mouse>(input.event.data).position;
        for (auto& element : _elements)
        {
            if (element.sprite->getRectangle()->contains(position))
            {
                element.selected = !element.selected;
                selection_changed = true;
                if (element.selected)
                    ++amount_selected;
            }
        }

        if (selection_changed)
        {
            if (amount_selected > 0)
                _selection_manager->fetch(this);
            else
                _selection_manager->remove(this);
        }
               
        break;
    }

    }
}

void ClassicMockNote::update(const kku::microsec& music_offset)
{
        switch (_state)
        {
        default: return;
            break;

        case State::FLYING:
            if (music_offset >= getPerfectOffset())
            {
                _state = State::DYING;
                for (auto& element : _elements)
                    element.animations[_state]->launch(element.sprite, music_offset, getPerfectOffset());
            }
            break;

        case State::DYING:
            if (_elements[0].animations[_state]->isDone())
                _state = State::DEAD;
            break;
        }

        for (auto& element : _elements)
            if (element.animations[_state])
                element.animations[_state]->update(music_offset);
}

std::vector<MockElement>& ClassicMockNote::getElements()
{
    return _elements;
}

void ClassicMockNote::deselect()
{
    for (auto& element : _elements)
        element.selected = false;
}
