#include "test_arena.h"
#include "wapp.h"
#include <stdlib.h>

#define ARENA_CAPACITY KB(16)

wapp_intern Arena *arena = nullptr;
wapp_intern i32 count    = 20;
wapp_intern i32 *array   = nullptr;

TestFuncResult test_arena_init(void) {
  b8 result = wapp_mem_arena_init(&arena, ARENA_CAPACITY);

  return wapp_tester_result(result);
}

TestFuncResult test_arena_init_succeeds_when_reserving_very_large_size(void) {
  Arena *large_arena = nullptr;
  u64 capacity       = GB(512);
  b8 result         = wapp_mem_arena_init(&large_arena, capacity);
  if (result) {
    wapp_mem_arena_destroy(&large_arena);
  }

  return wapp_tester_result(result);
}

TestFuncResult test_arena_alloc_succeeds_when_within_capacity(void) {
  array       = (i32 *)wapp_mem_arena_alloc(arena, count * sizeof(i32));
  b8 result  = array != nullptr;

  for (i32 i = 0; i < count; ++i) {
    array[i] = i * 10;
  }

  return wapp_tester_result(result);
}

TestFuncResult test_arena_alloc_fails_when_over_capacity(void) {
  u8 *bytes   = (u8 *)wapp_mem_arena_alloc(arena, ARENA_CAPACITY * 2);
  b8 result  = bytes == nullptr;

  return wapp_tester_result(result);
}

TestFuncResult test_arena_realloc_bigger_size(void) {
  u64 old_count = 10;
  u64 new_count = 20;
  i32 *bytes    = (i32 *)wapp_mem_arena_alloc(arena, old_count * sizeof(i32));

  for (u64 i = 0; i < old_count; ++i) {
    bytes[i] = (i32)i;
  }

  i32 *new_bytes = (i32 *)wapp_mem_arena_realloc(arena, bytes, old_count * sizeof(i32), new_count * sizeof(i32));
  if (!new_bytes) {
    return wapp_tester_result(false);
  }

  for (u64 i = 0; i < new_count; ++i) {
    if (i < old_count && new_bytes[i] != bytes[i]) {
      return wapp_tester_result(false);
    }
  }

  return wapp_tester_result(true);
}

TestFuncResult test_arena_realloc_smaller_size(void) {
  u64 old_count = 10;
  u64 new_count = 5;
  i32 *bytes    = (i32 *)wapp_mem_arena_alloc(arena, old_count * sizeof(i32));

  for (u64 i = 0; i < old_count; ++i) {
    bytes[i] = (i32)i;
  }

  i32 *new_bytes = (i32 *)wapp_mem_arena_realloc(arena, bytes, old_count * sizeof(i32), new_count * sizeof(i32));
  if (!new_bytes) {
    return wapp_tester_result(false);
  }

  for (u64 i = 0; i < new_count; ++i) {
    if (i < new_count && new_bytes[i] != bytes[i]) {
      return wapp_tester_result(false);
    }
  }

  return wapp_tester_result(true);
}

TestFuncResult test_arena_clear(void) {
  wapp_mem_arena_clear(arena);
  b8 result = true;

  for (i32 i = 0; i < count; ++i) {
    if (array[i] != 0) {
      result = false;
      break;
    }
  }

  return wapp_tester_result(result);
}

TestFuncResult test_arena_destroy(void) {
  wapp_mem_arena_destroy(&arena);
  b8 result = arena == nullptr;

  return wapp_tester_result(result);
}
