extends Node
class_name IntroScript

export (NodePath) var dialogue_box_path
onready var dialogue_box = get_node(dialogue_box_path)

export (NodePath) var ely_sprite_path
onready var ely_sprite = get_node(ely_sprite_path)

export (NodePath) var herbert_sprite_path
onready var herbert_sprite = get_node(herbert_sprite_path)

export (String, FILE, '*.json') var intro_dialogue : String

func _ready():
	assert(dialogue_box != null)
	assert(herbert_sprite != null)
	
	dialogue_box.connect('update', self, 'update_camera')
	
	yield(get_tree().create_timer(2.0), 'timeout')
	yield(start_dialogue(intro_dialogue), 'end')
	get_tree().change_scene("res://scenes/game1.tscn")

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_sprite.show()
		sprite = herbert_sprite
	else:
		herbert_sprite.hide()
		sprite = ely_sprite
	
	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()

func start_dialogue(dialog_path : String) -> DialogueAction:
	var dialogue = DialogueAction.new()
	dialogue.dialogue_file_path = dialog_path
	dialogue.dialogue_box = dialogue_box
	dialogue.start()
	return dialogue

var crab_finished = false
var crab_step = 0
func do_crab_step():
	crab_finished = false
	herbert_sprite.frame = 0
	if crab_step == 0:
		herbert_sprite.connect('animation_finished', self, 'crab_animation_finished')
		herbert_sprite.play('eyes')
		herbert_sprite.show()
	elif crab_step == 1:
		herbert_sprite.play('first_step')
	elif crab_step == 2:
		herbert_sprite.play('second_step')
	elif crab_step == 3:
		herbert_sprite.disconnect('animation_finished', self, 'crab_animation_finished')
		herbert_sprite.play('third_step')
		yield(herbert_sprite, 'animation_finished')
		herbert_sprite.play('idle')
		emit_signal("end_step")
	crab_step += 1

func crab_animation_finished():
	crab_finished = true

func _input(event):
	if crab_finished && event.is_action_pressed('ui_accept'):
		do_crab_step()
