extends Node

signal profile_changed(new_profile)

var current_profile_id = 0

var profiles = {
	0: 'keyboard',
	1: 'controller'
}

var keyboard = {}
var controller = {}

func change_profile(id):
	current_profile_id = id
	var profile = get(profiles[id])
	
	for action_name in profile.keys():
		change_action_key(action_name, profile[action_name])
	emit_signal('profile_changed', profile)
	return profile

func commit_to_changes():
	for profile_name in profiles.values():
		var profile = get(profile_name)
		for action_name in profile.keys():
			if(action_name.ends_with("_old")):
				continue
			erase_old_action_event(action_name)
			profile[action_name + "_old"] = profile[action_name]
			InputMap.action_add_event(action_name, profile[action_name])

func change_action_key(action_name, event, old_event = null) -> bool:
	if(old_event != null):
		if(event.as_text().match("*Joy*") != old_event.as_text().match("*Joy*")):
			return false
		get_selected_profile()[action_name+"_old"] = old_event
	get_selected_profile()[action_name] = event
	return true

func erase_old_action_event(action_name):
	if(get_selected_profile().has(action_name+"_old")):
		var old_event = get_selected_profile()[action_name+"_old"]
		var event = get_selected_profile()[action_name]
		if(old_event != event):
			InputMap.action_erase_event(action_name, old_event)

func initialize_profiles() -> void:
	var actions: Array = InputMap.get_actions()
	actions.sort()
	for action in actions:
		var input_events = InputMap.get_action_list(action)
		for event in input_events:
			if event.as_text().match("*JoypadButton*"):
				controller[action] = event
				controller[action+"_old"] = event
			elif !event.as_text().match("*Joy*"):
				keyboard[action] = event
				keyboard[action+"_old"] = event
	change_profile(current_profile_id)

func get_selected_profile():
	return get(profiles[current_profile_id])

func _on_ProfilesMenu_item_selected(ID):
	change_profile(ID)
