#include "engine.h"

Engine::Engine(std::string title, int width, int height)
{
    // convert title to char*
    ctitle = title.c_str();

    // Initialize SDL and TFF;
    TTF_Init();
    SDL_Init(SDL_INIT_EVERYTHING);

    // Create window and renderer
    window = SDL_CreateWindow(
        ctitle, 
        SDL_WINDOWPOS_CENTERED, 
        SDL_WINDOWPOS_CENTERED, 
        width, 
        height, 
        SDL_WINDOW_SHOWN
    );
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}

void Engine::initSound()
{
    // Initialize sound
    Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
    soundInitialized = true;
}

void Engine::clear(SDL_Color color)
{
    // Set color
    SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);

    // Clear screen
    SDL_RenderClear(renderer);
}

void Engine::startFrame()
{
    // Start frame
    frameStart = SDL_GetTicks();
}

void Engine::render()
{
    // Render screen
    SDL_RenderPresent(renderer);

    if (1000 / targetFrameRate > SDL_GetTicks() - frameStart)
    {
        SDL_Delay(1000 / targetFrameRate - (SDL_GetTicks() - frameStart));
    }
}

void Engine::update()
{
    // Update input
    input.update();
}

Engine::~Engine()
{
    // Free renderer and window
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    // If sound is initialized, quit Mix
    if (soundInitialized)
    {
        Mix_Quit();
    }

    // Quit SDL and TTF
    SDL_Quit();
    TTF_Quit();
}
