#include <iostream>
#include <algorithm>
#include <random>
#include "Game.hpp"
#include "SDL.h"
#include "SDL_ttf.h"
#include "words.hpp"
#include "utils.hpp"


void Game::Run() {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl;
        exit(-1);
    }
    if (TTF_Init() < 0) {
        std::cerr << "Failed to initialize TTF: " << TTF_GetError() << std::endl;
        exit(-1);
    }
    SDL_Window *window = SDL_CreateWindow("hang man", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_SIZE.x,
                                          SCREEN_SIZE.y, 0);
    if (window == nullptr) {
        std::cerr << "Failed to create SDL_Window with error: " << SDL_GetError() << std::endl;
        exit(-1);
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        std::cerr << "Failed to create SDL_Renderer with error: " << SDL_GetError() << std::endl;
        exit(-1);
    }
    SDL_RendererInfo rendererInfo;
    if (SDL_GetRendererInfo(renderer, &rendererInfo) == 0) {
        std::cout << "Using renderer: " << rendererInfo.name << std::endl;
    }

    SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    Game game;
    bool quit = false;
    SDL_Event event;
    while (!quit) {
        while (SDL_WaitEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    quit = true;
                    break;
                case SDL_KEYDOWN :
                    game.handle_key(event.key.keysym.sym);
            }
        }

    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
    SDL_Quit();
}

Game::Game() : guessed() {
    std::random_device random_device{};
    std::mt19937 rng(random_device());

    size_t words_len = array_len(words);
    this->all_words = std::vector<const char *>();
    this->all_words.reserve(words_len);
    for (int i = 0; i < words_len; i++)
        all_words.push_back(words[i]);
    std::shuffle(all_words.begin(), all_words.end(), rng);
}

void Game::handle_key(SDL_Keycode event) {

}

void Game::select_word() {

}
