extends Node

signal game_over

onready var background := $background
onready var foreground := $foreground
onready var spawner := $spawner
onready var player := $player2
onready var scoreUI := $scoreUI
onready var start_timer_UI := $start_timer_UI
onready var instructionsUI := $instructionsUI

var next_timeline_lose := ""
var next_timeline_win := ""

var game_mode = ""

var MUSIC = "res://music/mini_jeu.ogg"

func _ready():
	Signals.connect("die", self, "on_game_over")
	Signals.connect("win", self, "on_win")


func setup(mode: String, next_lose: String, next_win: String):
	print("minigame: " + mode + " " + next_lose + " " + next_win)
	set_mode(mode)
	scoreUI.init(mode)
	next_timeline_lose = next_lose
	next_timeline_win = next_win


func set_mode(mode: String):
	match mode:
		"score":
			game_mode = "score"
		"time":
			game_mode = "time"
		_:
			print("unkonwn mini-game mode")
	

func start():
	print("starting minigame")
	BackgroundMusic.crossfade_to(MUSIC, -10, 1)
	start_timer_UI.init()
	var t = Timer.new()
	t.set_wait_time(0.5)
	add_child(t)
	t.start()
	for n in range(3,0,-1):
		start_timer_UI.update_timer(String(n))
		yield(t, "timeout")
	start_timer_UI.update_timer("GO !")
	instructionsUI._init()
	foreground.start()
	player.start(game_mode)
	yield(t, "timeout")
	yield(t, "timeout")
	start_timer_UI.hide()
	spawner.start()
	scoreUI.start(game_mode)
	t.queue_free()


func stop():
	foreground.stop()
	player.stop()
	spawner.stop()
	

func on_win():
	stop()
	emit_signal("game_over", next_timeline_win)

func on_game_over():
	stop()
	emit_signal("game_over", next_timeline_lose)
