extends Spatial

var _is_free
var _x
var _y

var _neighbours

var _map

func _ready():
	_is_free = true
	_map = get_node("/root/Game_manager/Map")
	var material = SpatialMaterial.new()
	material.albedo_color = Color(1, 0.41, 0.71)
	$Cylinder.set_surface_material(0, material)

func set_coordinates(x, y):
	_x = x
	_y = y

func _on_Area_input_event(camera, event, click_position, click_normal, shape_idx):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.pressed:
			get_node("/root/Game_manager/Mouse_controller").left_click_on_hex(self)
		
		if event.button_index == BUTTON_RIGHT and event.pressed:
			get_node("/root/Game_manager/Mouse_controller").right_click_on_hex(self)

func set_color(color_id):
	var material = SpatialMaterial.new()
	if color_id == 0:
		material.albedo_color = Color(0, 0, 0)
	
	if color_id == 1:
		material.albedo_color = Color(0, 0, 1)
	
	if color_id == 2:
		material.albedo_color = Color(0, 1, 0)
	
	if color_id == 3:
		material.albedo_color = Color(0, 1, 1)
	
	if color_id == 4:
		material.albedo_color = Color(1, 0, 0)
	
	if color_id == 5:
		material.albedo_color = Color(1, 0, 1)
	
	if color_id == 6:
		material.albedo_color = Color(1, 1, 0)
	
	if color_id == 7:
		material.albedo_color = Color(1, 1, 1)
		
	$Cylinder.set_surface_material(0, material)

func occupy_hex():
	_is_free = false

func is_free():
	return _is_free

func is_any_neighbour_free():
	var is_free = false
	for neighbour in get_neighbours():
		if neighbour.is_free():
			is_free = true
			continue
	return is_free

func get_neighbours():
	if _neighbours == null:
		_neighbours = []

		# left neighbour
		if _x > 0:
			_neighbours.append(_map.get_hex_at(_x - 1, _y))
		
		# odd-row, starting below
		##########
		if _y % 2 == 0:
			# top left neighbour if(y%2)
			if _x > 0 && _y < _map._map_height - 1:
				_neighbours.append(_map.get_hex_at(_x - 1, _y + 1))
			
			# top right neighbour if(y%2)
			if _y < _map._map_height - 1:
				_neighbours.append(_map.get_hex_at(_x, _y + 1))
			
			# bottom right neighbour if(y%2)
			if _y > 0:
				_neighbours.append(_map.get_hex_at(_x, _y - 1));
				# bottom left neighbour if(y%2)
			if _x > 0 && _y > 0:
				_neighbours.append(_map.get_hex_at(_x - 1, _y - 1));
		##########
		else:
			# top left neighbour 
			if _y < _map._map_height - 1:
				_neighbours.append(_map.get_hex_at(_x, _y + 1));
			
			# top right neighbour 
			if _x < _map._map_width - 1 && _y < _map._map_height - 1:
				_neighbours.append(_map.get_hex_at(_x + 1, _y + 1))
				# bottom right neighbour
			if _x < _map._map_width - 1 && _y > 0:
				_neighbours.append(_map.get_hex_at(_x + 1, _y - 1))
			
				# bottom left neighbour
			if _y > 0:
				_neighbours.append(_map.get_hex_at(_x, _y - 1))
			
		##########
		## right neighbour
		if _x < _map._map_width - 1:
			_neighbours.append(_map.get_hex_at(_x + 1, _y))
	
	return _neighbours
