class_name BindingLoaderType extends Node
## Handles persisting action input bindings.

const BINDINGS_FILE := "user://bindings.tres"


func _ready() -> void:
	# Map may not be defined if no keybinds have been written
	if FileAccess.file_exists(BINDINGS_FILE):
		print_debug("Reading keybinds from ", BINDINGS_FILE)
		var map: BindingMap = load(BINDINGS_FILE) as BindingMap

		# Overwrite InputMap with loaded bindings
		for action: StringName in map.bindings.keys():
			# Clear existing bindings
			InputMap.action_erase_events(action)
			# Apply loaded binding
			var event: InputEvent = map.bindings[action]
			if event:
				InputMap.action_add_event(action, event)


func write() -> void:
	# Build map from input actions
	var map: BindingMap = BindingMap.new()
	for action: StringName in InputMap.get_actions():
		var events := InputMap.action_get_events(action)
		if events:
			map.bindings[action] = events[0]
		else:
			map.bindings[action] = null

	# Write to disk
	print_debug("Writing keybinds to ", BINDINGS_FILE)
	ResourceSaver.save(map, BINDINGS_FILE)
