extends BaseLevel

class_name TestLevel

export var init_yarn_script : Resource

func _ready():
	yarnRunner.add_command("Spawn", funcref(self, "spawn"))
	yarnRunner.add_command("EnableTrigger", funcref(self, "enable_trigger"))
	yarnRunner.add_command("Scene", funcref(self, "scene"))
	
	EventDispatcher.connect("trigger_script", self, "trigger_script")
	
	Controller.hud.show()
	Controller.player_infos.reset()
	
	trigger_script(init_yarn_script)

func spawn(args):
	yield(get_tree(), "idle_frame")
	
	if args.size() < 1:
		printerr("Spawn command take at least one parameter for target")
		return
	
	var spawner = get_node("Spawners/" + args[0])
	if spawner != null and spawner.has_method("spawn"):
		spawner.spawn()
	else:
		print("spawner " + args[0] + " not found or not compatible")
	
func enable_trigger(args):
	yield(get_tree(), "idle_frame")
	
	if args.size() < 1:
		printerr("EnableTrigger command take at least one parameter for target")
		return
	
	var trigger = get_node("Triggers/" + args[0])
	if trigger != null and trigger.has_method("enable"):
		trigger.enable()
		print("trigger " + args[0] + " enabled")
	else:
		print("trigger " + args[0] + " not found or not compatible")

func trigger_script(yarn_script):
	print("script triggered")
	
	yarnRunner.say_func = funcref(Controller.speech_panel.text, "on_new_line")
	yarnRunner.choices_func = funcref(Controller.speech_panel.choices, "on_choices")
	
	Controller.speech_panel.show()
	Controller.player_input_enabled = false
	
	yarnRunner.yarnScript = yarn_script
	yield(yarnRunner.run_all(), "completed")
	
	Controller.speech_panel.hide()
	Controller.player_input_enabled = true

func scene(args):
	yield(get_tree(), "idle_frame")
	
	if args.size() < 1:
		printerr("Scene command take at least one parameter for target")
		return
	
	print("Request new scene : " + args[0])
	emit_signal("request_new_scene", args[0])

func _exit_tree():
	Controller.hud.hide()
	Controller.speech_panel.hide()


func _on_Switch_switch(activated):
	$DirectionalLight.light_energy = activated if 1 else 0
