extends Control

var GAUGE_PREFIX = "jauge_"
var RELATIONS_PREFIX = "relation_"
var CHOICES_PREFIX = "choix_"

var gauges_names := ["travail", "education", "financier", "ecologie", "social"]
var relations_names := ["evelyne", "jm"]
var choices_names := ["tel_ouvert"]

var gauges_ranges := [[-11, 14], [-9, 23], [-23, 24], [-13, 16], [-16, 17]]
var relations_ranges := [[-5, 6], [-3, 5]]

var gauges_values := []
var relations_values := []

var gauges := {}
var relations := {}
var choices := {}

onready var progress_container = $VBoxContainer/Control/RecapContainer/MarginContainer/Panel/MarginContainer/VBoxContainer/MarginContainer/GaugesContainer
onready var main_container = $VBoxContainer/Control
onready var recap_container = $VBoxContainer/Control/RecapContainer
onready var gauges_timer = $GaugesTimer

var shown_gauge_index = 0

func _ready():
	progress_container.connect("mouse_entered", self, '_on_mouse_entered')
	progress_container.connect("mouse_exited", self, '_on_mouse_exited')
	_recover_variables()
	gauges_values = _get_percentages(gauges, gauges_names, gauges_ranges)
	relations_values = _get_percentages(relations, relations_names, relations_ranges)
	
	print(gauges_values)
	print(relations_values)
	
	gauges_timer.start()


func _on_mouse_exited():
	main_container.move_child(recap_container, 0)
	
  
func _on_mouse_entered():
	# Make sure the recap is behind the characters
	# This allows showing the infobox above the recap
	main_container.move_child(recap_container, 1)


func _recover_variables():
	var definitions = Dialogic.get_definitions()
	# Get relations and gauges from variables
	for d in definitions["variables"]:
		for g in gauges_names:
			if d["name"] == GAUGE_PREFIX + g:
				gauges[g] = d
		for r in relations_names:
			if d["name"] == RELATIONS_PREFIX + r:
				relations[r] = d
		for c in choices_names:
			if d["name"] == CHOICES_PREFIX + c:
				choices[c] = d
	print(gauges)
	print("--")
	print(relations)
	print("--")
	print(choices)


func _get_percentages(data: Dictionary, names: Array, ranges: Array) -> Array:
	var final_array := []
	for i in range(0, data.size()):
		var val = float(data[names[i]]["value"])
		var min_max = ranges[i]
		# Adjust offset
		val -= min_max[0]
		# Get whole range
		var total_range = min_max[1] - min_max[0]
		final_array.append(100 * val / total_range)
	return final_array


func _on_GaugesTimer_timeout():
	var c = progress_container.get_child(shown_gauge_index)
	c.progress = gauges_values[shown_gauge_index]
	shown_gauge_index += 1
	if shown_gauge_index >= progress_container.get_child_count():
		gauges_timer.stop()


func _on_ExitButton_pressed():
	get_tree().change_scene("res://scenes/MainMenu.tscn")
