// Inludes
#include <SDL.h>
#include <string>
#include <vector>
#include "input.h"
#include "text.h"
#include "sprite.h"

// Variables
SDL_Surface* assets;
int startTime = 0;
Input input;
TTF_Font *font;
SDL_Window *window;
SDL_Renderer *renderer;
const int targetFps = 60;

// Functions
// Quit function
void quit()
{
    // Free assets
    TTF_CloseFont(font);
    SDL_FreeSurface(assets);   
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    TTF_Quit();
    // Exit program
    exit(0);
}

// Main function
int main(int argc, char* argv[])
{   
    // Initialize SDL and TFF;
    TTF_Init();
    SDL_Init(SDL_INIT_VIDEO);

    // Create window and renderer
    window = SDL_CreateWindow("test game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 400, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    // Load assets
    assets = SDL_LoadBMP("assets/sprites.bmp");

    // frame map
    std::map<std::string, SDL_Rect> frames = {
            { "idle", { 4, 456, 68, 125 } },
            { "idle2", { 76, 456, 68, 128 } },
            { "idle3", { 148, 456, 68, 125 } }
    };

    // Create sprite and animation
    Sprite* sprite = new Sprite(renderer, assets);
    AnimationManager* animations = new AnimationManager(sprite);
    animations->addAnimation("idle", frames, 10, false, true, true, true);
    animations->setAnimation("idle");

    // Main loop
    while (true)
    {
        // Start time
        startTime = SDL_GetTicks();

        // Update input
        input.update();

        // Exit if window is closed
        if (input.exit)
        {
            quit();
        }

        // Update animation
        animations->update();

        // Clear screen
        SDL_SetRenderDrawColor(renderer, 100, 100, 255, 255);
        SDL_RenderClear(renderer);  

        // Draw sprite
        animations->draw(renderer);

        // Update screen
        SDL_RenderPresent(renderer);

        // if frame is faster than target fps, delay
        if (1000 / targetFps > SDL_GetTicks() - startTime)
        {
            SDL_Delay(1000 / targetFps - (SDL_GetTicks() - startTime));
        }
    }
    return 0;
}