#include <isogfx/isogfx.h>

#include <filesystem.h>
#include <mempool.h>

#include <linux/limits.h>

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/// Maximum number of tiles unless the user chooses a non-zero value.
#define DEFAULT_MAX_NUM_TILES 1024

// -----------------------------------------------------------------------------
// Tile set (TS) and tile map (TM) file formats.
// -----------------------------------------------------------------------------

/// Maximum length of path strings in .TS and .TM files.
#define MAX_PATH_LENGTH 128

typedef struct Ts_Tile {
  uint16_t width;     /// Tile width in pixels.
  uint16_t height;    /// Tile height in pixels.
  Pixel    pixels[1]; /// Count: width * height.
} Ts_Tile;

typedef struct Ts_TileSet {
  uint16_t num_tiles;
  uint16_t max_tile_width;  /// Maximum tile width in pixels.
  uint16_t max_tile_height; /// Maximum tile height in pixels.
  Ts_Tile  tiles[1];        /// Count: num_tiles.
} Ts_TileSet;

typedef struct Tm_Layer {
  union {
    char tileset_path[MAX_PATH_LENGTH]; // Relative to the Tm_Map file.
  };
  Tile tiles[1]; /// Count: world_width * world_height.
} Tm_Layer;

typedef struct Tm_Map {
  uint16_t world_width;  /// World width in number of tiles.
  uint16_t world_height; /// World height in number of tiles.
  uint16_t base_tile_width;
  uint16_t base_tile_height;
  uint16_t num_layers;
  Tm_Layer layers[1]; // Count: num_layers.
} Tm_Map;

static inline const Tm_Layer* tm_map_get_next_layer(
    const Tm_Map* map, const Tm_Layer* layer) {
  assert(map);
  assert(layer);
  return (const Tm_Layer*)((const uint8_t*)layer + sizeof(Tm_Layer) +
                           ((map->world_width * map->world_height - 1) *
                            sizeof(Tile)));
}

static inline const Ts_Tile* ts_tileset_get_next_tile(
    const Ts_TileSet* tileset, const Ts_Tile* tile) {
  assert(tileset);
  assert(tile);
  return (const Ts_Tile*)((const uint8_t*)tile + sizeof(Ts_Tile) +
                          ((tile->width * tile->height - 1) * sizeof(Pixel)));
}

// -----------------------------------------------------------------------------
// Renderer state.
// -----------------------------------------------------------------------------

// typedef Ts_Tile TileData;

typedef struct TileData {
  uint16_t width;
  uint16_t height;
  uint16_t num_blocks;   // Number of pixel blocks in the pixels mempool.
  uint16_t pixels_index; // Offset into the pixels mempool.
} TileData;

DEF_MEMPOOL_DYN(TilePool, TileData)
DEF_MEMPOOL_DYN(PixelPool, Pixel)

typedef struct IsoGfx {
  int       screen_width;
  int       screen_height;
  int       tile_width;
  int       tile_height;
  int       world_width;
  int       world_height;
  Tile*     world;
  Pixel*    screen;
  TilePool  tiles;
  PixelPool pixels;
} IsoGfx;

// -----------------------------------------------------------------------------
// Math and world / tile / screen access.
// -----------------------------------------------------------------------------

typedef struct ivec2 {
  int x, y;
} ivec2;

typedef struct vec2 {
  double x, y;
} vec2;

static inline ivec2 ivec2_add(ivec2 a, ivec2 b) {
  return (ivec2){.x = a.x + b.x, .y = a.y + b.y};
}

static inline ivec2 ivec2_scale(ivec2 a, int s) {
  return (ivec2){.x = a.x * s, .y = a.y * s};
}

static inline ivec2 iso2cart(ivec2 iso, int s, int t, int w) {
  return (ivec2){
      .x = (iso.x - iso.y) * (s / 2) + (w / 2), .y = (iso.x + iso.y) * (t / 2)};
}

// Method 1.
// static inline vec2 cart2iso(vec2 cart, int s, int t, int w) {
//  const double x    = cart.x - (double)(w / 2);
//  const double xiso = (x * t + cart.y * s) / (double)(s * t);
//  return (vec2){
//      .x = (int)(xiso), .y = (int)((2.0 / (double)t) * cart.y - xiso)};
//}

// Method 2.
static inline vec2 cart2iso(vec2 cart, int s, int t, int w) {
  const double one_over_s = 1. / (double)s;
  const double one_over_t = 1. / (double)t;
  const double x          = cart.x - (double)(w / 2);
  return (vec2){
      .x = (one_over_s * x + one_over_t * cart.y),
      .y = (-one_over_s * x + one_over_t * cart.y)};
}

static const Pixel* tile_xy_const_ref(
    const IsoGfx* iso, const TileData* tile, int x, int y) {
  assert(iso);
  assert(tile);
  assert(x >= 0);
  assert(y >= 0);
  assert(x < tile->width);
  assert(y < tile->height);
  return &mempool_get_block(
      &iso->pixels, tile->pixels_index)[y * tile->width + x];
}

static Pixel tile_xy(const IsoGfx* iso, const TileData* tile, int x, int y) {
  return *tile_xy_const_ref(iso, tile, x, y);
}

static Pixel* tile_xy_mut(const IsoGfx* iso, TileData* tile, int x, int y) {
  return (Pixel*)tile_xy_const_ref(iso, tile, x, y);
}

static inline const Tile* world_xy_const_ref(const IsoGfx* iso, int x, int y) {
  assert(iso);
  assert(x >= 0);
  assert(y >= 0);
  assert(x < iso->world_width);
  assert(y < iso->world_height);
  return &iso->world[y * iso->world_width + x];
}

static inline Tile world_xy(const IsoGfx* iso, int x, int y) {
  return *world_xy_const_ref(iso, x, y);
}

static inline Tile* world_xy_mut(IsoGfx* iso, int x, int y) {
  return (Tile*)world_xy_const_ref(iso, x, y);
}

static inline const Pixel* screen_xy_const_ref(
    const IsoGfx* iso, int x, int y) {
  assert(iso);
  assert(x >= 0);
  assert(y >= 0);
  assert(x < iso->screen_width);
  assert(y < iso->screen_height);
  return &iso->screen[y * iso->screen_width + x];
}

static inline Pixel screen_xy(IsoGfx* iso, int x, int y) {
  return *screen_xy_const_ref(iso, x, y);
}

static inline Pixel* screen_xy_mut(IsoGfx* iso, int x, int y) {
  return (Pixel*)screen_xy_const_ref(iso, x, y);
}

// -----------------------------------------------------------------------------
// Renderer, world and tile management.
// -----------------------------------------------------------------------------

IsoGfx* isogfx_new(const IsoGfxDesc* desc) {
  assert(desc->screen_width > 0);
  assert(desc->screen_height > 0);
  // Part of our implementation assumes even widths and heights for precision.
  assert((desc->screen_width & 1) == 0);
  assert((desc->screen_height & 1) == 0);

  IsoGfx* iso = calloc(1, sizeof(IsoGfx));
  if (!iso) {
    return 0;
  }

  iso->screen_width  = desc->screen_width;
  iso->screen_height = desc->screen_height;

  const int screen_size = desc->screen_width * desc->screen_height;

  if (!(iso->screen = calloc(screen_size, sizeof(Pixel)))) {
    goto cleanup;
  }

  return iso;

cleanup:
  isogfx_del(&iso);
  return 0;
}

/// Destroy the world and its tile set.
static void destroy_world(IsoGfx* iso) {
  assert(iso);
  if (iso->world) {
    free(iso->world);
    iso->world = 0;
  }
  mempool_del(&iso->tiles);
  mempool_del(&iso->pixels);
}

void isogfx_del(IsoGfx** pIso) {
  assert(pIso);
  IsoGfx* iso = *pIso;
  if (iso) {
    destroy_world(iso);
    if (iso->screen) {
      free(iso->screen);
      iso->screen = 0;
    }
    free(iso);
    *pIso = 0;
  }
}

bool isogfx_make_world(IsoGfx* iso, const WorldDesc* desc) {
  assert(iso);
  assert(desc);
  assert(desc->tile_width > 0);
  assert(desc->tile_height > 0);
  // Part of our implementation assumes even widths and heights for greater
  // precision.
  assert((desc->tile_width & 1) == 0);
  assert((desc->tile_height & 1) == 0);

  // Handle recreation by destroying the previous world.
  destroy_world(iso);

  iso->tile_width   = desc->tile_width;
  iso->tile_height  = desc->tile_height;
  iso->world_width  = desc->world_width;
  iso->world_height = desc->world_height;

  const int world_size      = desc->world_width * desc->world_height;
  const int tile_size       = desc->tile_width * desc->tile_height;
  const int tile_size_bytes = tile_size * (int)sizeof(Pixel);
  const int tile_pool_size =
      desc->max_num_tiles > 0 ? desc->max_num_tiles : DEFAULT_MAX_NUM_TILES;

  if (!(iso->world = calloc(world_size, sizeof(Tile)))) {
    goto cleanup;
  }
  if (!mempool_make_dyn(&iso->tiles, tile_pool_size, tile_size_bytes)) {
    goto cleanup;
  }

  return true;

cleanup:
  destroy_world(iso);
  mempool_del(&iso->tiles);
  return false;
}

bool isogfx_load_world(IsoGfx* iso, const char* filepath) {
  assert(iso);
  assert(filepath);

  bool success = false;

  // Handle recreation by destroying the previous world.
  destroy_world(iso);

  // Load the map.
  printf("Load tile map: %s\n", filepath);
  Tm_Map* map = read_file(filepath);
  if (!map) {
    goto cleanup;
  }

  // Allocate memory for the map and tile sets.
  const int world_size           = map->world_width * map->world_height;
  const int base_tile_size       = map->base_tile_width * map->base_tile_height;
  const int base_tile_size_bytes = base_tile_size * (int)sizeof(Pixel);
  // TODO: Need to get the total number of tiles from the map.
  const int tile_pool_size = DEFAULT_MAX_NUM_TILES;

  if (!(iso->world = calloc(world_size, sizeof(Tile)))) {
    goto cleanup;
  }
  if (!mempool_make_dyn(&iso->tiles, tile_pool_size, sizeof(TileData))) {
    goto cleanup;
  }
  if (!mempool_make_dyn(&iso->pixels, tile_pool_size, base_tile_size_bytes)) {
    goto cleanup;
  }

  // Load the tile sets.
  const Tm_Layer* layer = &map->layers[0];
  // TODO: Handle num_layers layers.
  for (int i = 0; i < 1; ++i) {
    const char* ts_path = layer->tileset_path;

    // Tile set path is relative to the tile map file. Make it relative to the
    // current working directory before loading.
    char ts_path_cwd[PATH_MAX] = {0};
    if (!make_relative_path(MAX_PATH_LENGTH, filepath, ts_path, ts_path_cwd)) {
      goto cleanup;
    }

    Ts_TileSet* tileset = read_file(ts_path_cwd);
    if (!tileset) {
      goto cleanup;
    };

    // Load tile data.
    const Ts_Tile* tile = &tileset->tiles[0];
    for (uint16_t j = 0; j < tileset->num_tiles; ++j) {
      // Tile dimensions should be a multiple of the base tile size.
      assert((tile->width % map->base_tile_width) == 0);
      assert((tile->height % map->base_tile_height) == 0);

      const uint16_t tile_size = tile->width * tile->height;

      // TODO: Add function in mempool to alloc N consecutive blocks.
      const int num_blocks = tile_size / base_tile_size;
      Pixel*    pixels     = mempool_alloc(&iso->pixels);
      assert(pixels);
      // This is ugly and assumes that blocks are allocated consecutively.
      for (int b = 1; b < num_blocks; ++b) {
        Pixel* block = mempool_alloc(&iso->pixels);
        assert(block);
      }
      memcpy(pixels, tile->pixels, tile_size * sizeof(Pixel));

      TileData* tile_data = mempool_alloc(&iso->tiles);
      assert(tile_data);
      tile_data->width      = tile->width;
      tile_data->height     = tile->height;
      tile_data->num_blocks = (uint16_t)num_blocks;
      tile_data->pixels_index =
          (uint16_t)mempool_get_block_index(&iso->pixels, pixels);

      tile = ts_tileset_get_next_tile(tileset, tile);
    }

    printf("Loaded tile set (%u tiles): %s\n", tileset->num_tiles, ts_path_cwd);

    free(tileset);
    layer = tm_map_get_next_layer(map, layer);
  }

  // Load the map into the world.
  layer = &map->layers[0];
  // TODO: Handle num_layers layers.
  for (int i = 0; i < 1; ++i) {
    memcpy(iso->world, layer->tiles, world_size * sizeof(Tile));

    // TODO: We need to handle 'firsgid' in TMX files.
    for (int j = 0; j < world_size; ++j) {
      iso->world[j] -= 1;
    }

    layer = tm_map_get_next_layer(map, layer);
  }

  iso->world_width  = map->world_width;
  iso->world_height = map->world_height;
  iso->tile_width   = map->base_tile_width;
  iso->tile_height  = map->base_tile_height;

  success = true;

cleanup:
  if (map) {
    free(map);
  }
  if (!success) {
    destroy_world(iso);
  }
  return success;
}

int isogfx_world_width(const IsoGfx* iso) {
  assert(iso);
  return iso->world_width;
}

int isogfx_world_height(const IsoGfx* iso) {
  assert(iso);
  return iso->world_height;
}

/// Create a tile mask procedurally.
static void make_tile_from_colour(
    const IsoGfx* iso, Pixel colour, TileData* tile) {
  assert(iso);
  assert(tile);

  const int width  = tile->width;
  const int height = tile->height;
  const int r      = width / height;

  for (int y = 0; y < height / 2; ++y) {
    const int mask_start = width / 2 - r * y - 1;
    const int mask_end   = width / 2 + r * y + 1;
    for (int x = 0; x < width; ++x) {
      const bool  mask = (mask_start <= x) && (x <= mask_end);
      const Pixel val = mask ? colour : (Pixel){.r = 0, .g = 0, .b = 0, .a = 0};

      // Top half.
      *tile_xy_mut(iso, tile, x, y) = val;

      // Bottom half reflects the top half.
      const int y_reflected                   = height - y - 1;
      *tile_xy_mut(iso, tile, x, y_reflected) = val;
    }
  }
}

Tile isogfx_make_tile(IsoGfx* iso, const TileDesc* desc) {
  assert(iso);
  assert(desc);
  // Client must create world before creating tiles.
  assert(iso->tile_width > 0);
  assert(iso->tile_height > 0);

  TileData* tile = mempool_alloc(&iso->tiles);
  assert(tile); // TODO: Make this a hard assert.

  tile->width  = desc->width;
  tile->height = desc->height;

  switch (desc->type) {
  case TileFromColour:
    make_tile_from_colour(iso, desc->colour, tile);
    break;
  case TileFromFile:
    assert(false); // TODO
    break;
  case TileFromMemory:
    assert(false); // TODO
    break;
  }

  return (Tile)mempool_get_block_index(&iso->tiles, tile);
}

void isogfx_set_tile(IsoGfx* iso, int x, int y, Tile tile) {
  assert(iso);
  *world_xy_mut(iso, x, y) = tile;
}

void isogfx_set_tiles(IsoGfx* iso, int x0, int y0, int x1, int y1, Tile tile) {
  assert(iso);
  for (int y = y0; y < y1; ++y) {
    for (int x = x0; x < x1; ++x) {
      isogfx_set_tile(iso, x, y, tile);
    }
  }
}

// -----------------------------------------------------------------------------
// Rendering and picking.
// -----------------------------------------------------------------------------

static void draw_tile(IsoGfx* iso, ivec2 origin, Tile tile) {
  assert(iso);

  const TileData* tile_data = mempool_get_block(&iso->tiles, tile);
  assert(tile_data);

  // Tile can exceed screen bounds, so we must clip it.
#define max(a, b) (a > b ? a : b)
  const int py_offset = max(0, (int)tile_data->height - origin.y);
  origin.y            = max(0, origin.y - (int)tile_data->height);

  // Clip along Y and X as we draw.
  for (int py = py_offset;
       (py < tile_data->height) && (origin.y + py < iso->screen_height); ++py) {
    const int sy = origin.y + py - py_offset;
    for (int px = 0;
         (px < tile_data->width) && (origin.x + px < iso->screen_width); ++px) {
      const Pixel colour = tile_xy(iso, tile_data, px, py);
      if (colour.a > 0) {
        const int sx                = origin.x + px;
        *screen_xy_mut(iso, sx, sy) = colour;
      }
    }
  }

  //  for (int py = 0; py < tile_data->height; ++py) {
  //    for (int px = 0; px < tile_data->width; ++px) {
  //      const Pixel colour = tile_xy(iso, tile_data, px, py);
  //      if (colour.a > 0) {
  //        const int sx = origin.x + px;
  //        const int sy = origin.y + py;
  //        if ((sx >= 0) && (sy >= 0) && (sx < iso->screen_width) &&
  //            (sy < iso->screen_height)) {
  //          *screen_xy_mut(iso, sx, sy) = colour;
  //        }
  //      }
  //    }
  //  }
}

static void draw(IsoGfx* iso) {
  assert(iso);

  const int W = iso->screen_width;
  const int H = iso->screen_height;

  memset(iso->screen, 0, W * H * sizeof(Pixel));

  // const ivec2 o = {(iso->screen_width / 2) - (iso->tile_width / 2), 0};
  const ivec2 o = {
      (iso->screen_width / 2) - (iso->tile_width / 2), iso->tile_height};
  const ivec2 x = {.x = iso->tile_width / 2, .y = iso->tile_height / 2};
  const ivec2 y = {.x = -iso->tile_width / 2, .y = iso->tile_height / 2};

  // TODO: Culling.
  // Ex: map the screen corners to tile space to cull.
  // Ex: walk in screen space and fetch the tile.
  // The tile-centric approach might be more cache-friendly since the
  // screen-centric approach would juggle multiple tiles throughout the scan.
  for (int ty = 0; ty < iso->world_height; ++ty) {
    for (int tx = 0; tx < iso->world_width; ++tx) {
      const Tile  tile = world_xy(iso, tx, ty);
      const ivec2 so =
          ivec2_add(o, ivec2_add(ivec2_scale(x, tx), ivec2_scale(y, ty)));
      draw_tile(iso, so, tile);
    }
  }
}

void isogfx_pick_tile(
    const IsoGfx* iso, double xcart, double ycart, int* xiso, int* yiso) {
  assert(iso);
  assert(xiso);
  assert(yiso);

  const vec2 xy_iso = cart2iso(
      (vec2){.x = xcart, .y = ycart}, iso->tile_width, iso->tile_height,
      iso->screen_width);

  if ((0 <= xy_iso.x) && (xy_iso.x < iso->world_width) && (0 <= xy_iso.y) &&
      (xy_iso.y < iso->world_height)) {
    *xiso = (int)xy_iso.x;
    *yiso = (int)xy_iso.y;
  } else {
    *xiso = -1;
    *yiso = -1;
  }
}

void isogfx_render(IsoGfx* iso) {
  assert(iso);
  draw(iso);
}

void isogfx_draw_tile(IsoGfx* iso, int x, int y, Tile tile) {
  assert(iso);
  assert(x >= 0);
  assert(y >= 0);
  assert(x < iso->world_width);
  assert(y < iso->world_height);

  const ivec2 o  = {(iso->screen_width / 2) - (iso->tile_width / 2), 0};
  const ivec2 vx = {.x = iso->tile_width / 2, .y = iso->tile_height / 2};
  const ivec2 vy = {.x = -iso->tile_width / 2, .y = iso->tile_height / 2};
  const ivec2 so =
      ivec2_add(o, ivec2_add(ivec2_scale(vx, x), ivec2_scale(vy, y)));

  draw_tile(iso, so, tile);
}

bool isogfx_resize(IsoGfx* iso, int screen_width, int screen_height) {
  assert(iso);
  assert(iso->screen);

  const int current_size = iso->screen_width * iso->screen_height;
  const int new_size     = screen_width * screen_height;

  if (new_size > current_size) {
    Pixel* new_screen = calloc(new_size, sizeof(Pixel));
    if (new_screen) {
      free(iso->screen);
      iso->screen = new_screen;
    } else {
      return false;
    }
  }
  iso->screen_width  = screen_width;
  iso->screen_height = screen_height;
  return true;
}

const Pixel* isogfx_get_screen_buffer(const IsoGfx* iso) {
  assert(iso);
  return iso->screen;
}