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

namespace game
{
    static int param_count = 0;
    static char **params = nullptr;
    static bool should_exit = false;

    static unsigned int ticks_per_frame = 1000/60;

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

    void exit()
    {
        should_exit = true;
    }

    const char* getParams(const int index)
    {
        if (index<param_count) return params[index];
        return nullptr;
    }
}

int main(int argc, char *argv[])
{
    game::param_count = argc;
    game::params = argv;

    SDL_Init(SDL_INIT_EVERYTHING);
    
    input::init();
    audio::init();
    game::init();

    static unsigned int current_ticks = SDL_GetTicks();

    SDL_Event e;
    while (!game::should_exit)
    {
        while(SDL_PollEvent(&e))
        {
            if (e.type==SDL_QUIT) { game::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 (e.type==SDL_CONTROLLERBUTTONDOWN) {
                input::updatePadBtn(e.cbutton.button);
                input::updatePadBtnPressed(e.cbutton.button);
            }
        }

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

    audio::quit();
    draw::quit();

    return 0;
}