extends Control

export (PackedScene) var template = load("res://scenes/UI/choose_scenes/parts/Template.tscn")

func _ready():
	_load_button_access_scenes()

## PRIVATE
func _load_button_access_scenes():
	for row_index in range(0, Global.database.get_table_by_name("levels").m_rows_count):
		_apply_scene(load("res://db/MLevel.gd").new(row_index), row_index)

func _apply_scene(level, index):
	$MarginContainer.add_child(_load_scene(level.name()))
	var node = _build_path(level.name())
	
	_configure_select(level, node)
	configure_reset(level, node, index, false)
	configure_counter(level, node)

func _load_scene(name):
	var template_instance = template.instance()
	template_instance.set_name(name)
	
	return template_instance

func _build_path(name):
	return "MarginContainer/"+name

func _build_method(name):
	return "_on_"+name.to_lower()+"_pressed"

func _load_texture(thumbnail):
	return load(thumbnail)

func _configure_select(level, node):
	var selector = get_node(node+"/MarginContainer/CenterAlign/MainButton")
	var thumbnail = get_node(node+"/MarginContainer/CenterAlign/MainButton/MarginStich/ThumbnailLevel")
	
	thumbnail.set_texture(_load_texture(level.thumbnail()))
	selector.connect("pressed", Event, _build_method(level.name()))

func configure_reset(level, node, index, animate):
	var reset = get_node(node+"/MarginContainer/CenterAlign/MainButton/TabAlign/ButtonReset")
	var animation = get_node(node+"/AnimationPlayer")
	if int(level.object_finding()) == 0:
		_configure_reset_disable(animation, reset, animate)
	else:
		_configure_reset_enable(animation, reset, level, node, index)

func _configure_reset_disable(animation, reset, animate = false):
	animation.play("SlideReset")
	if !animate:
		animation.seek(1, false)
	
	reset.set_disabled(true)
	reset.set_default_cursor_shape(CURSOR_ARROW)
	if reset.is_connected("pressed", Event, "_on_reset_level"):
		reset.disconnect("pressed", Event, "_on_reset_level")

func _configure_reset_enable(animation, reset, level, node, index):
	animation.play_backwards("SlideReset")
	reset.set_disabled(false)
	reset.set_default_cursor_shape(CURSOR_POINTING_HAND)
	reset.connect("pressed", Event, "_on_reset_level", [level, node, index, self])

func configure_counter(level, node):
	var count = get_node(node+"/MarginContainer/CenterAlign/MainButton/TabAlign/ButtonCount/MarginBottom/Label")
	
	count.set_text(level.object_finding()+" / "+level.object_to_find())
