extends Control

onready var _action_list = $"%ActionKeyList"
onready var changes_made := false
onready var changes_saved := false

func _ready() -> void:
	$InputMapper.connect('profile_changed', self, 'rebuild')
	$InputMapper.initialize_profiles()
	$ProfilesMenu.initialize($InputMapper)
	$InputMapper.change_profile($ProfilesMenu.selected)

func rebuild(input_profile):
	_action_list.clear()
	var first = true
	for input_action in input_profile.keys():
		if(input_action.ends_with("_old") || input_action.begins_with(("ui_"))):
			continue
		var line = _action_list.add_input_line(input_action, input_profile[input_action])
		if first:
			$ProfilesMenu.focus_neighbour_bottom = line.get_child(2).get_path()
			$Back.focus_neighbour_top = line.get_child(2).get_path()
			$Save.focus_neighbour_top = line.get_child(2).get_path()
			$Reset.focus_neighbour_top = line.get_child(2).get_path()
			first = false
		line.get_child(2).focus_neighbour_left = $Back.get_path()
		line.get_child(2).focus_neighbour_right = $Save.get_path()
		line.connect('change_button_pressed', self, '_on_InputLine_change_button_pressed', [input_action, line])

func close():
	self.visible = false
	$"%PauseOverlay".visible = true
	$"%PauseOverlay/VBoxContainer/Continue".grab_focus()

func _on_InputLine_change_button_pressed(action_name, line):
	var old_event = $InputMapper.get_selected_profile()[action_name]
	$"%KeySelectMenu".open()
	var event = yield($"%KeySelectMenu", "key_selected")
	if event == null:
		return
	if($InputMapper.change_action_key(action_name, event, old_event)):
		changes_made = true
		changes_saved = false
		line.update_key(event)
