extends Node

var comPort: String = "COM8"

var time: float
var pulseTime: float

# min ideal setup interval 0.05 and duration 0.03
@export_range(0, 0.5) var pulseInterval: float = 0.2
@export_range(0, 0.1) var pulseDuration: float = 0.03

@export var colorRect: ColorRect

var pendingPulses: float = 0

func _ready():
	var arguments = {}
	for argument in OS.get_cmdline_args():
		if argument.find("=") > -1:
			var key_value = argument.split("=")
			arguments[key_value[0].lstrip("--")] = key_value[1]
		else:
			# Options without an argument will be present in the dictionary,
			# with the value set to an empty string.
			arguments[argument.lstrip("--")] = ""
	
	var hasComPort = arguments.has("port")
	if (hasComPort):
		comPort = arguments["port"]
	
	Vibration.Init(comPort)


func _process(delta):
	if (time > 0):
		time -= delta
		if (time <= 0):
			Vibration.UnSendVibration()
	
	if (pendingPulses > 0 and pulseTime > 0):
		pulseTime -= delta
		if (pulseTime <= 0):
			_sendPulse(pendingPulses - 1)


func shakeController(ammount: int):
	_sendPulse(ammount)
	var tween = get_tree().create_tween()
	tween.tween_property(colorRect, "color", Color(Color.WHITE, 1), 0.05)
	tween.tween_property(colorRect, "color", Color(Color.WHITE, 0), 0.05)


func _sendPulse(ammount: int):
	pendingPulses = ammount - 1
	time = pulseDuration
	pulseTime = pulseInterval
	Vibration.SendVibration()
