extends Control
# @see https://www.gotut.net/godot-key-bindings-tutorial/


var input_action = null


func _ready():
	self.set_keys()


func _input(event):
	if self.is_input_event(event) and input_action != null:
		self.change_key(self.input_action, event)


func is_input_event(event):
	# TODO: read up on proper controller input handling
	return event is InputEventKey or event is InputEventJoypadButton or event is InputEventJoypadMotion


func set_keys():
	for action in Enum.ACTIONS:
		var input = get_node("Panel/VBoxContainer/" + str(action) + "/Input")
		input.set_pressed(false)
		
		var action_list = InputMap.action_get_events(action)
		if action_list.is_empty():
			input.set_text("SET BUTTON")
		else:
			var text = ""
			for idx in range(action_list.size()):
				var btn = action_list[idx]
				var btn_text = btn.as_text()
				
				if btn is InputEventJoypadButton:
					btn_text = "BtnIdx: " + str(btn.button_index)
				elif btn is InputEventJoypadMotion:
					btn_text = "JoyAxis: " + str(btn.axis_value)
				
				if idx == 0:
					text += btn_text
				else:
					text += ", " + btn_text
			
			input.set_text(text)


func change_key(action, key):
	if key is InputEventJoypadMotion:
		if key.get_axis_value() > 0:
			key.set_axis_value(1)
		else:
			key.set_axis_value(-1)
	
	InputMap.action_add_event(action, key)
	self.input_action = null
	self.set_keys()


func clear_keys(action):
	InputMap.action_erase_events(action)
	self.set_keys()


func _on_Clear_pressed(action):
	self.clear_keys(action)


func _on_Input_pressed(action):
	self.input_action = action