extends Spatial

onready var map = get_node("/root/Level/Map")
onready var characters = get_node("/root/Level/Map/Characters")
onready var money = get_node("/root/Level/Map/Money")
onready var utils = get_node("/root/Level/Map/Utils")

func make_turn(position : Vector3):
	if map.is_connected_to_house(position, map.current_player_tile()):
		var mouse_position_character_and_player_ids = characters.find_character_and_player_ids_on(position)
		if map.get_tile_cell(position) == map.current_player_tile() and \
		   mouse_position_character_and_player_ids != null and \
		   mouse_position_character_and_player_ids[0] == characters.current_player and \
		   not characters.is_current_player_character_used(mouse_position_character_and_player_ids[1]):
			characters.switch_character_to(mouse_position_character_and_player_ids[0], 
										   mouse_position_character_and_player_ids[1])
		elif characters.is_current_character_exist():
			map.move_to_tile(position)

func upgrade_character_on_position(position : Vector3):
	var character_on_position = characters.find_character_on(position)
	if character_on_position != null and \
	   map.get_tile_cell(position) == map.current_player_tile() and \
	   money.count_connected_money(position, map.current_player_tile()) \
		 >= money.CHARACTER_UPGRADE_COSTS[character_on_position.level] and \
	   character_on_position.upgrade():
		money.spend_connected_money(position, map.current_player_tile(), money.CHARACTER_COST)

func try_spawn_character(position : Vector3):
	if map.get_tile_cell(position) == map.current_player_tile() and \
	   map.get_building_cell(position) == GridMap.INVALID_CELL_ITEM and \
	   map.is_connected_to_house(position, map.current_player_tile()) and \
	   characters.find_character_and_player_ids_on(position) == null and \
	   money.count_connected_money(position, map.current_player_tile()) >= money.CHARACTER_COST:
		
		money.spend_connected_money(position, map.current_player_tile(), money.CHARACTER_COST)
		
		characters.spawn_current_player_character(position)
		
		if characters.current_character + 1 == characters.current_player_characters_count():
			characters.current_character_obj().active = true

func _physics_process(_delta):
	if Input.is_action_just_released("turn"):
		make_turn(utils.world_to_grid_position(utils.mouse_position()))
	
	if Input.is_action_just_released("upgrade"):
		upgrade_character_on_position(utils.world_to_grid_position(utils.mouse_position()))
		
	if Input.is_action_just_released("pass"):
		characters.set_next_player()
		
	if Input.is_action_just_released("spawn"):
		try_spawn_character(utils.world_to_grid_position(utils.mouse_position()))
