extends Node2D

export var id = 0
export var is_hiden = false

var type = "actor"
var _name = ""
var alias = ""
var dialogue = -1
var has_quests = false
var is_conversing  = false
var _atack = false

var actions = []

func on_start_dialogue():
	var player_pos_x = Global.player.global_position.x
	
	if global_position.x - player_pos_x > 0:
		$sprite.scale.x = -1
	else:
		$sprite.scale.x = 1
	Interaction.check_objective("talk", alias, -1)
	$ico.frame = 3
	
func on_task_completed():
	$ico.frame = 0
		
func on_complete_the_quest():
	$ico.frame = 2
	dialogue = 0
	has_quests = false

func on_cancel_dialogue():
	if has_quests:
		$ico.frame = 1
	else:
		$ico.frame = 2
	is_conversing = false
	$AnimationPlayer.play("idle")
	
func on_conversing(state):
	is_conversing = state
	conversing_anim(state)
		
func set_new_dialogue(id):
	dialogue = id
	update_ico()
	
func update_ico():
	if has_quests:
		$ico.frame = 1
	elif dialogue > 0:
		$ico.frame = 2
	else:
		$ico.frame = 2
		
func conversing_anim(conversing_state):
	if conversing_state:
		$AnimationPlayer.play("speak")
		is_conversing = true
	else:
		$AnimationPlayer.play("idle")
		is_conversing = false
	
func random_action():
	var wait_time = randi() % 6
	
	if !is_conversing and !_atack:
		var r = randi() % (actions.size() + 1)
		var siding = randi() % 2 
		var next_anim = ""
		if siding == 0:
			$sprite.scale.x = -1
		else:
			$sprite.scale.x = 1
		if r == actions.size():
			next_anim = "idle"
		else:
			next_anim = actions[r]
		$AnimationPlayer.play(next_anim)
		yield($AnimationPlayer,"animation_finished")
	yield(get_tree().create_timer(wait_time),"timeout")
	random_action()
	
func _play_sound():
	Audio.play_sound("speak", false)
	
func atack(a):
	var player = Global.player
	var player_pos_x = player.global_position.x
	var anim_player = $AnimationPlayer
	
	_atack = true
	if global_position.x - player_pos_x > 0:
		$sprite.scale.x = -1
	else:
		$sprite.scale.x = 1
	anim_player.play("atack")
	Audio.play_sound("kick", false)
	yield(anim_player,"animation_finished")
	player.apply_damage(20)
	anim_player.play("idle")
	_atack = false

func show_actor(a):
	print("show")
	visible = true
	$interract/CollisionShape2D.disabled = false
	
func hide_actor(a):
	visible = false
	$interract/CollisionShape2D.disabled = true
	
func _load():
	var data = Interaction.get_actor_data(id)
	var array = $AnimationPlayer.get_animation_list()
	
	_name = data["name"]
	alias = data["alias"]
	dialogue = data["dialogue"]
	has_quests = (data["quests"].size() > 0)
	for a in array:
		if a.begins_with("action"):
			actions.append(a)
	$sprite.texture = load("res://sprites/actors/" + alias + ".png")
	Interaction.actors.append({actor_id = id, body = self})
	update_ico()
	
func _ready():
	_load()
	random_action()
	if is_hiden:
		hide_actor(false)
