#include "application.h"
#include "inputtype.h"

#include "classicgame/classicgame.h"
#include "classicgame/classicgraphicsmanager.h"

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

Application::Application() :
    _game_window({1280, 720}, "Test", sf::Style::Default),
    _game(std::make_unique<ClassicGame>(std::make_unique<ClassicGraphicsManager>(_game_window)))
{
    _game_window.setFramerateLimit(60);
    _game_window.setKeyRepeatEnabled(false);
    _game_window.setMouseCursorGrabbed(false);
    _game_window.setVerticalSyncEnabled(true);
}

void Application::run()
{
    _game_window.display();
    _game->run();

    exec();
}

void Application::exec()
{
    sf::Clock timer;
    sf::Clock game_timer;
    sf::Time time_since_last_update = sf::Time::Zero;

    while (_game_window.isOpen())
    {

        time_since_last_update += timer.restart();

        input();

        bool isOneFramePassed = time_since_last_update >= TIME_PER_FRAME;
        if (isOneFramePassed)
        {
            time_since_last_update -= TIME_PER_FRAME;
            game_timer.restart();
            update();
            draw();
        }
    }
}

void Application::input()
{
    sf::Event event;
    while (_game_window.pollEvent(event))
    {
        switch(event.type)
        {
        case sf::Event::Closed:
            _game_window.close();
            break;

        case sf::Event::KeyPressed:
        case sf::Event::KeyReleased:
            if (event.key.code == sf::Keyboard::Escape)
                _game_window.close();
            _game->input(PlayerInput{0, event});
            break;

        default:
            break;
        }
    }
}

void Application::update()
{
    _game->update();
}

void Application::draw()
{
    _game_window.clear();
    _game->draw();
    _game_window.display();
}