#include "application/gamestate.h"
#include "widgets/button.h"
#include "widgets/group.h"

#include "core/game.h"

GameState::GameState(const std::shared_ptr<kku::CoreFactory>& core_factory, const std::shared_ptr<kku::Game>& game, Callbacks&& callbacks) :
    _core_factory(core_factory),
    _game(game),
    _onLeaveGameCallback(callbacks.onLeaveGame)
{
}

void GameState::input(const kku::SystemEvent& event)
{
    switch (event.type)
    {
    default:
        break;

    case kku::SystemEvent::Type::KeyRelease:
        const auto view = std::get<kku::SystemEvent::Key>(event.data).view;
        if (view == kku::SystemEvent::Key::Code::Space)
            _music->isPlaying() ? _music->pause() : _music->play();
        if (view == kku::SystemEvent::Key::Code::Escape)
        {
            _onLeaveGameCallback();
            return;
        }
    }

    if (_music->isPlaying())
        _game->input(kku::GameEvent{_music->fetchOffset(), event});
}

void GameState::update(const kku::microsec& dt)
{
    _game->update(kku::UpdateData{_music->fetchOffset(), dt});
}

void GameState::display() const
{
    _game->display();
}

void GameState::enter()
{
    _game->run();

    _music = _core_factory->getMusic();
    _music->open("resources/METEOR.flac");
    _music->setVolume(10);
    _music->play();
}

void GameState::leave()
{
    _music.reset();
}
