extends Node

const TOGGLE_MOUSE_BUTTON: StringName = &"toggle_mouse"

var using_controller: bool = false


func _input(event: InputEvent) -> void:
	if not window_focused():
		get_viewport().set_input_as_handled()
		return

	if event is InputEventMouseButton or event is InputEventKey:
		if using_controller:
			using_controller = false
	elif event is InputEventJoypadButton or event is InputEventJoypadMotion:
		if not using_controller:
			using_controller = true

	if event.is_action_pressed(TOGGLE_MOUSE_BUTTON):
		toggle_mouse()


func window_focused() -> bool:
	return DisplayServer.window_is_focused()


func toggle_mouse() -> void:
	Input.set_mouse_mode(
		Input.MOUSE_MODE_CAPTURED
		if Input.mouse_mode == Input.MOUSE_MODE_VISIBLE
		else Input.MOUSE_MODE_VISIBLE
	)


func set_mouse_captured(captured: bool) -> void:
	(capture_mouse if captured else release_mouse).call()


func capture_mouse() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED


func release_mouse() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
