# Hurry Curry! - a game about cooking
# Copyright (C) 2026 Hurry Curry! Contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
extends Node

func _ready() -> void:
	Input.joy_connection_changed.connect(joy_check)

static var banned_words: PackedStringArray = [
	"touchpad", "trackpad", "clickpad", "mouse", "pen", "finger", "led",
	"Synaptics",
]

static func joy_check(device: int, connected: bool) -> void:
	if not connected:
		return
	var device_name: String = Input.get_joy_name(device)
	if not is_banned(device_name):
		return
	var guid: String = Input.get_joy_guid(device)
	var mapping: String = guid + ',' + device_name.replace(',', '')
	Input.add_joy_mapping(mapping, true)
	for axis: JoyAxis in range(JOY_AXIS_SDL_MAX) as Array[JoyAxis]:
		var event: InputEventJoypadMotion = InputEventJoypadMotion.new()
		event.device = device
		event.axis = axis
		Input.parse_input_event(event)
	for button_index: JoyButton in range(JOY_BUTTON_SDL_MAX) as Array[JoyButton]:
		var event: InputEventJoypadButton = InputEventJoypadButton.new()
		event.device = device
		event.button_index = button_index
		Input.parse_input_event(event)
	prints('Ignoring joypad device:', mapping)

static func is_banned(device_name: String) -> bool:
	for word: String in banned_words:
		var i: int = device_name.findn(word)
		if i < 0:
			continue
		if i > 0 and not is_ascii_non_letter(device_name[i - 1]):
			continue
		var j: int = i + word.length()
		if j < device_name.length() and not is_ascii_non_letter(device_name[j]):
			continue
		return true
	return false

static func is_ascii_non_letter(c: String) -> bool:
	return c.unicode_at(0) < 128 and not (c >= 'a' and c <= 'z' or c >= 'A' and c <= 'Z')
