#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "character.h"
#include "heap.h"
#include "util.h"

static int32_t character_turn_cmp(const void *key, const void *with) {
  if (((character *) key)->next_turn == ((character *) with)->next_turn) {
    return ((character *) key)->seq_num - ((character *) with)->seq_num;
  } else {
    return ((character *) key)->next_turn - ((character *) with)->next_turn;
  }
}

char characteristics_symbols[] = "0123456789abcdef";

character::character(uint8_t x, uint8_t y) {
  pos.x = x;
  pos.y = y;
  
  speed = 0;
  seq_num = 0;
  next_turn = 0;
  alive = 1;
  symbol = ' ';
}

character::~character() { }

bool character::is_player() {
  return false;
}

int character::has_characteristic(int bit) {
  return 0;
}

monster::monster(uint8_t x, uint8_t y) : character(x, y) {
  static int next_seq = 1;
  uint32_t characteristics = rand() & 0x0000000f;
  
  this->characteristics = characteristics;
  
  // Initialize the starting "last seen" position to the position of the monster
  // This will keep smart monsters from moving until they actually see the player
  last_seen.x = x;
  last_seen.y = y;
  
  speed = randrange(5, 20);
  seq_num = next_seq++;
  symbol = characteristics_symbols[characteristics];
}

bool monster::is_player() {
  return false;
}

int monster::has_characteristic(int bit) {
  return characteristics & bit;
}

player_character::player_character(uint8_t x, uint8_t y) : character(x, y){
  speed = 10;
  seq_num = 0;
  symbol = '@';
}

bool player_character::is_player() {
  return true;
}

int player_character::has_characteristic(int bit) {
  return 0;
}

void init_character_turn_heap(heap_t *h) {
  heap_init(h, character_turn_cmp, NULL);
}