#include "assets.hpp"
#include "texture.hpp"
#include <SDL_image.h>
#include <SDL_pixels.h>
#include <SDL_render.h>
#include <config.hpp>
#include <iostream>
#include <phoenix.hpp>
#include <state.hpp>

GlobalState state;

void PRunBoostrap() {
  PLoadTextureAsset("assets/textures/wall_brick.png");
  PLoadTextureAsset("assets/textures/floor.png");
}

PhoenixGame::PhoenixGame() {

  SDL_Init(SDL_INIT_VIDEO);
  IMG_Init(IMG_INIT_PNG);

  state.window = SDL_CreateWindow("Phoenix", SDL_WINDOWPOS_CENTERED,
                                  SDL_WINDOWPOS_CENTERED, 1000, 1000, 0);

  state.renderer = SDL_CreateRenderer(
      state.window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);

  // Load textures
  PRunBoostrap();

  m_currentMap = PLoadMapFromFile("maps/dm_scale.map");
  m_viewport = {0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2};
}

void PhoenixGame::present() {
  SDL_RenderSetViewport(state.renderer, &m_viewport);
  SDL_RenderPresent(state.renderer);
}

void PhoenixGame::render() {

  SDL_RenderSetScale(state.renderer, m_currentMap.mapScaleX,
                     m_currentMap.mapScaleY);
  SDL_SetRenderDrawColor(state.renderer, 0, 0, 0, 255);
  SDL_RenderClear(state.renderer);

  PRenderMap(&m_currentMap);

  //  PRenderTexture(&m_texture, 0, 0);
}

void PhoenixGame::run() {
  mb_isOpen = true;

  while (mb_isOpen) {
    SDL_Event event;

    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        mb_isOpen = false;
        break;
      }
    }

    unsigned char const *keys = SDL_GetKeyboardState(nullptr);
    if (keys[SDL_SCANCODE_UP]) {
      m_viewport.w += 5;
      m_viewport.h += 5;
    } else if (keys[SDL_SCANCODE_DOWN]) {
      m_viewport.w -= 5;
      m_viewport.h -= 5;
    } else if (keys[SDL_SCANCODE_W]) {
      m_viewport.y += 20;
      if (m_viewport.y > 0)
        m_viewport.y = 0;
    } else if (keys[SDL_SCANCODE_S]) {
      m_viewport.y -= 20;
      if (m_viewport.y < -720)
        m_viewport.y = -720;
    } else if (keys[SDL_SCANCODE_A]) {
      m_viewport.x += 20;
    } else if (keys[SDL_SCANCODE_D]) {
      m_viewport.x -= 20;
      if (m_viewport.x < -1280)
        m_viewport.x = -1280;
    }

    // Rendering code

    render();
    present();

    // End rendering code
  }
}
