@tool
extends Node
@onready var box_spawner: BoxSpawner = $BoxSpawner
@onready var ul1_3: BeltConveyorAssembly = $UL1_3

var tag_group = "TagGroup0"

func _ready() -> void:
	SimulationEvents.simulation_started.connect(_on_simulation_started)

func _on_simulation_started() -> void:
	# Register tags for EPC1
	OIPComms.register_tag(tag_group, "UL1_3_EPC1.CTRL.STS.Log.LEN", 1)
	OIPComms.register_tag(tag_group, "UL1_3_EPC1.HMI.STATE", 1)
	
	# Register tags for EPC2
	OIPComms.register_tag(tag_group, "UL1_3_EPC2.CTRL.STS.Log.LEN", 1)
	OIPComms.register_tag(tag_group, "UL1_3_EPC2.HMI.STATE", 1)
	
	# Register all 82 DATA tags for both EPCs
	for i in range(82):
		# EPC1 data tags
		var data_tag_epc1 = "UL1_3_EPC1.CTRL.STS.Log.DATA[" + str(i) + "]"
		OIPComms.register_tag(tag_group, data_tag_epc1, 1)
		
		# EPC2 data tags
		var data_tag_epc2 = "UL1_3_EPC2.CTRL.STS.Log.DATA[" + str(i) + "]"
		OIPComms.register_tag(tag_group, data_tag_epc2, 1)

func _physics_process(delta: float) -> void:
	if ul1_3.speed == 0:
		box_spawner.disable = true
	else:
		box_spawner.disable = false
		
	# Monitor both EPCs
	var epc1_state = OIPComms.read_int32(tag_group, "UL1_3_EPC1.HMI.STATE")
	var epc2_state = OIPComms.read_int32(tag_group, "UL1_3_EPC2.HMI.STATE")

	# Monitor both EPCs - UNCOMMENT TO SEE
	#print("EPC1 State: ", epc1_state)
	#print("EPC1 Log String: ", Utils.read_string(tag_group, "UL1_3_EPC1.CTRL.STS.Log"))
	#
	#print("EPC2 State: ", epc2_state)
	#print("EPC2 Log String: ", Utils.read_string(tag_group, "UL1_3_EPC2.CTRL.STS.Log"))
