extends Node2D

onready var ely = $CampfireBackground
onready var herbert = $Herbert
onready var dialogue_box = $UI/Dialogue
onready var the_choice = $TheChoice

export (String, FILE, '*.json') var end_1_dialogue
export (String, FILE, '*.json') var end_truth_dialogue
export (String, FILE, '*.json') var end_lie_dialogue

func _ready():
	assert(end_1_dialogue != null)
	assert(end_truth_dialogue != null)
	assert(end_lie_dialogue != null)
	
	dialogue_box.connect('update', self, 'update_camera')
	
	yield(dialogue_box.start_dialogue(end_1_dialogue), 'end')
	the_choice.show()
	the_choice.play('default')

var choice = -1

func make_choice(choice : int):
	the_choice.hide()
	yield(dialogue_box.start_dialogue(end_truth_dialogue if choice == 0 else end_lie_dialogue), 'end')

func _input(event):
	if the_choice.visible:
		if event.is_action_pressed("right"):
			the_choice.play('lie')
			choice = 1
		if event.is_action_pressed("left"):
			the_choice.play('truth')
			choice = 0
		if event.is_action_pressed("ui_accept"):
			if choice >= 0:
				make_choice(choice)

func update_camera():
	var animation = dialogue_box.expression
	if animation == "":
		animation = "idle"
	
	var sprite : AnimatedSprite
	if dialogue_box.character_name == 'Crab' || dialogue_box.character_name == 'Herbert':
		herbert.show()
		sprite = herbert
	else:
		herbert.hide()
		sprite = ely
	
	var is_old_animation_loop = sprite.get_sprite_frames().get_animation_loop(sprite.get_animation())
	var is_new_animation_loop = sprite.get_sprite_frames().get_animation_loop(animation)
	if !is_old_animation_loop || !is_new_animation_loop:
		sprite.frame = 0
	
	sprite.play(animation)
	
	if !is_new_animation_loop:
		yield(sprite, 'animation_finished')
		dialogue_box.stop_waiting()
