#include "applicationsfml.h"
#include "sfml/corefactorysfml.h"
#include "sfml/application/inputconvertersfml.h"

#include <SFML/System/Clock.hpp>

const sf::Time TIME_PER_FRAME = sf::seconds(1.f / 90.f);

ApplicationSFML::ApplicationSFML(sf::RenderWindow * const render_window) :
    _render_window(render_window)
{
    _render_window->setFramerateLimit(60);
    _render_window->setKeyRepeatEnabled(false);
    _render_window->setMouseCursorGrabbed(false);
    _render_window->setVerticalSyncEnabled(true);

    _core_factory = std::make_shared<CoreFactorySFML>(_render_window);
}

void ApplicationSFML::display()
{
    _render_window->clear();

    for (const auto& state : _state_stack)
        state->display();

    _render_window->display();
}

void ApplicationSFML::run()
{
    sf::Clock timer;
    sf::Time time_since_last_update = sf::Time::Zero;

    while (_render_window->isOpen())
    {
        time_since_last_update += timer.restart();

        sf::Event event;
        while (_render_window->pollEvent(event))
        {
            switch(event.type)
            {
            case sf::Event::Closed:
                _render_window->close();
                break;

            default:
                Application::input(kku::convert(event));
                break;
            }
        }

        bool isOneFramePassed = time_since_last_update >= TIME_PER_FRAME;
        if (isOneFramePassed)
        {
            time_since_last_update -= TIME_PER_FRAME;
            update(time_since_last_update.asMicroseconds());
            display();
        }
    }
}
