#include <stdio.h>
#include <flecs.h>


#define BZ_ENTRYPOINT
#include <breeze.h>


typedef struct Game {
    Camera2D camera;
    BzTileset terrainTileset;
    BzTileset buildingsTileset;
    BzTileMap map;
} Game;

static Game GAME = {};

bool init(Game *game) {
    game->terrainTileset = bzTilesetCreate( &(BzTilesetDesc) {
        .path="assets/terrain.tsj",
        .texturePath="assets/terrain.png"
    });
    game->buildingsTileset = bzTilesetCreate(&(BzTilesetDesc) {
        .path="assets/buildings.tsj",
        .texturePath="assets/buildings.png"
    });

    game->map = bzTileMapCreate(&(BzTileMapDesc) {
        .path="assets/maps/test.tmj",
        .tilesets[0]=game->terrainTileset,
        .tilesets[1]=game->buildingsTileset
    });


    int screenWidth = 1280;
    int screenHeight = 720;

    game->camera = (Camera2D){ 0 };
    game->camera.target = (Vector2) {0, 0};
    game->camera.offset = (Vector2) {screenWidth / 2.0f, screenHeight / 2.0f};
    game->camera.rotation = 0.0f;
    game->camera.zoom = 1.0f;
    return true;
}
void deinit(Game *game) {
    bzTilesetDestroy(&game->terrainTileset);
    bzTilesetDestroy(&game->buildingsTileset);
    bzTileMapDestroy(&game->map);
}
void render(float dt, Game *game) {
    Camera2D *camera = &game->camera;
    if (IsKeyDown(KEY_W)) camera->target.y -= 20;
    if (IsKeyDown(KEY_S)) camera->target.y += 20;
    if (IsKeyDown(KEY_A)) camera->target.x -= 20;
    if (IsKeyDown(KEY_D)) camera->target.x += 20;

    if (IsKeyDown(KEY_Q)) camera->rotation--;
    if (IsKeyDown(KEY_E)) camera->rotation++;

    camera->zoom += ((float)GetMouseWheelMove() * 0.05f);

    BeginMode2D(*camera);
    ClearBackground(RAYWHITE);

    bzTileMapDraw(&game->map);

    EndMode2D();

    if (nk_begin(NK, "Show", nk_rect(50, 50, 220, 220),
                 NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) {
        // fixed widget pixel width
        nk_layout_row_static(NK, 30, 80, 1);
        if (nk_button_label(NK, "button")) {
            // event handling
        }
    }
    nk_end(NK);
}

bool bzMain(BzAppDesc *appDesc, int argc, const char **argv) {
    appDesc->width = 1280;
    appDesc->height = 720;
    appDesc->title = "PixelDefense";
    appDesc->fps = 60;

    appDesc->init = (BzAppInitFunc) init;
    appDesc->deinit = (BzAppDeinitFunc) deinit;
    appDesc->render = (BzAppRenderFunc) render;

    appDesc->userData = &GAME;
    appDesc->useNuklear = true;

    return true;
}
