#include "../include/raylib-cpp.hpp"
#include "entities/entitybase.hpp"
#include "render/textures.hpp"

void PlayerController(Entity &e, float deltatime) {
  raylib::Vector2 acceleration = {0,0};
  if (IsKeyDown(KEY_W)) acceleration.y--;
  if (IsKeyDown(KEY_A)) acceleration.x--;
  if (IsKeyDown(KEY_S)) acceleration.y++;
  if (IsKeyDown(KEY_D)) acceleration.x++;

  acceleration.Normalize();

  e.rect.x += acceleration.x * 100 * deltatime;

  e.rect.y += acceleration.y * 100 * deltatime;
}

int main() {
    int screenWidth = 1920;
    int screenHeight = 1080;


    raylib::Window window(screenWidth, screenHeight, "raylib-cpp - basic window");

    SetTargetFPS(60);

        Texture Texturemissing = GenDefaultTexture(); 

        raylib::Rectangle playerrect{screenWidth / 2.0f, screenHeight / 2.0f,64,64};
        Entity player{1, playerrect, "MainPlayer", 100, 100};
        player.controller = PlayerController;
        player.spriteid = 0;

        entityTextures.LoadImage("./src/assets/playersprite.png");
        tileTextures.LoadImage("./src/assets/BasicTile.png");

        Camera2D camera = { 0 };
        camera.offset = { screenWidth/2.0f, screenHeight/2.0f };
        camera.rotation = 0.0f;
        camera.zoom = 1.0f;
        
    
    while (!window.ShouldClose())
    {
        float deltatime = GetFrameTime();

        player.Update(deltatime);

        BeginDrawing();
        window.ClearBackground(BLACK);

        BeginMode2D(camera);

        camera.target = { player.rect.x + player.rect.width / 2.0f, player.rect.y + player.rect.height / 2.0f};

        if (IsKeyDown(KEY_Q)) camera.zoom += 0.1f;

        DrawText("Middle", 190, 200, 20, WHITE);

        Texture bg = tileTextures.GetTexture(0);

        // Infinite Background
        int bh = bg.height;
        int bw = bg.width;
        int offsetX = ((int)camera.target.x % bg.width);
        int offsetY = ((int)camera.target.y % bg.height);

        for (int i = -1; i <= GetScreenWidth() / bw + 1; i++) {
          for (int j = -1; j <= GetScreenHeight() / bh + 1; j++) {
            DrawTexture(
                bg,
                camera.target.x - offsetX - screenWidth / 2.0f + i * bw,
                camera.target.y - offsetY - screenHeight / 2.0f + j * bh,
                WHITE
            );
          }
        }

        player.Draw();

        EndMode2D();
        EndDrawing();
    }

    // UnloadTexture() and CloseWindow() are called automatically.

    return 0;
}
