#include "jgame.h"
#include "jdraw.h"
#include "jinput.h"
#include <SDL2/SDL.h>
#include <map>

namespace game
{
    static bool (*loop)() = nullptr;
    static unsigned int ticks_per_frame = 1000/60;
    static std::map<std::string, int> config;

    void setUpdateTicks(const int ticks)
    {
        ticks_per_frame = ticks;
    }

    void setState(bool (*loop)())
    {
        game::loop = loop;
    }

    void setConfig(const char* key, const int value)
    {
        config[key] = value;
    }

    const int getConfig(const char* key)
    {
        return config[key];
    }
}

int main(int argc, char *argv[])
{
    game::init();
    input::init(draw::getZoom());

    static unsigned int current_ticks = SDL_GetTicks();

    bool should_exit=false;
    SDL_Event e;
    while (!should_exit)
    {
        while(SDL_PollEvent(&e))
        {
            if (e.type==SDL_QUIT) { should_exit = true; break; }
            if (e.type==SDL_KEYDOWN)
            {
                input::updateKey(e.key.keysym.scancode);
            }
            if (e.type==SDL_KEYUP)
            {
                input::updateKeypressed(e.key.keysym.scancode);
            }
            if (e.type==SDL_MOUSEBUTTONUP)
            {
                input::updateClk(e.button.button);
            }
            if (e.type==SDL_MOUSEWHEEL)
            {
                input::updateWheel(e.wheel.y);
            }
        }

        if (SDL_GetTicks()-current_ticks >= game::ticks_per_frame)
        {
            if (game::loop) if (!game::loop()) should_exit = true;
            input::updateKey(SDL_SCANCODE_UNKNOWN);
            input::updateKeypressed(SDL_SCANCODE_UNKNOWN);
            input::updateClk(0);
            input::updateWheel(0);
            current_ticks = SDL_GetTicks();
        }
    }
    return 0;
}