extends Control
class_name RemapController

@export var min_time_between_remaps := 0.4
@export var remap_buttons_holder : VBoxContainer

var remap_button : Button
var remap_action : String

var time_since_remap := 0.0
var is_remapping := false

func _unhandled_key_input(event):
	if remap_button != null and event.pressed:
		remap_key(event)
	pass

func _input(event):
	if remap_button != null:
		if event is InputEventMouseButton and event.pressed:
			remap_key(event)
		if event is InputEventJoypadButton and event.pressed:
			remap_key(event)
		if event is InputEventJoypadMotion:
			remap_key(event)
	pass
	
func _ready():
	set_process_unhandled_key_input(false)
	remap_button = null
	pass
	
func _process(delta):
	if remap_button == null:
		time_since_remap += delta
		if is_remapping and time_since_remap > min_time_between_remaps:
			is_remapping = false
	pass
	
func start_remap(button : Button, action : String):
	if(is_remapping): return
	is_remapping = true
	if(remap_button != null):
		remap_button.display_key()
	remap_button = button
	remap_action = action
	remap_button.text = "..."
	remap_button.disabled = true
	set_process_unhandled_key_input(true)
	button.release_focus()
	pass

func remap_key(event):
	match str(event.get_class()):
		"InputEventJoypadButton":
			Save.game_data.controls["%s" % [remap_action]] = "b" + str(event.button_index)
		"InputEventJoypadMotion":
			if abs(event.axis_value) < 0.5: return
			Save.game_data.controls["%s" % [remap_action]] = "j" + str(event.axis) +  str("/1.00" if event.axis_value > 0 else "/-1.00")
		"InputEventMouseButton":
			Save.game_data.controls["%s" % [remap_action]] = "m" + str(event.button_index)
		"InputEventKey":
			Save.game_data.controls["%s" % [remap_action]] = event.keycode
	set_process_unhandled_key_input(false)
	for key in InputMap.action_get_events(remap_action):
		InputMap.action_erase_event(remap_action, key)
	InputMap.action_add_event(remap_action, event)
	remap_button.display_key()
	remap_button.grab_focus()
	remap_button.disabled = false
	time_since_remap = 0
	remap_button = null
	pass

func _on_reset_button_pressed():
	GlobalSettings.reset_controls_to_save_file()
	for child in remap_buttons_holder.get_children():
		if child is Button and child.is_in_group("RemappableButton"):
			child.display_key()
	pass
