@tool
extends Node
@onready var box_spawner: BoxSpawner = $"../BoxSpawner"
@onready var ul_1_3: BeltConveyorAssembly = $"../UL1_3"
@onready var hmi_start_pb: PushButton = $"../HMI_UL1_3_JR_PB1"
@onready var hmi_ul_1_3_jr_pb_2: PushButton = $"../HMI_UL1_3_JR_PB2" 
var color_1
var color_2
var tag_group = "TagGroup0"
var hmi_start_color_1 = "UL1_3_JR_PB1.HMI.Start_Color"
var hmi_start_color_2 = "UL1_3_JR_PB2.HMI.Start_Color"
var display_color_1
var display_color_2

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

func _on_simulation_started() -> void:
	OIPComms.register_tag(tag_group,hmi_start_color_1,1)
	OIPComms.register_tag(tag_group,hmi_start_color_2,1)
	OIPComms.register_tag(tag_group, "UL1_3_JR_PB1.CTRL.STS.Log.LEN", 1)
	
	# Register all 82 DATA tags
	for i in range(82):
		var data_tag = "UL1_3_JR_PB1.CTRL.STS.Log.DATA[" + str(i) + "]"
		OIPComms.register_tag(tag_group, data_tag, 1)

func read_string(tag_group_name: String, base_tag_name: String) -> String:
	"""Reads the log string from PLC DATA array"""
	var result = ""
	
	# Construct the length and data tag names
	var len_tag = base_tag_name + ".LEN"
	var data_tag = base_tag_name + ".DATA"
	
	# Read the actual string length from PLC (if available)
	var string_length = OIPComms.read_int32(tag_group_name, len_tag)
	
	# Limit to 82 max and ensure it's valid
	if string_length <= 0 or string_length > 82:
		string_length = 82
	
	# Read each character
	for i in range(string_length):
		var data_tag_indexed = data_tag + "[" + str(i) + "]"
		var char_value = OIPComms.read_int8(tag_group_name, data_tag_indexed)
		
		# Check for null terminator or invalid ASCII

		
		# Convert SINT to ASCII character
		if char_value > 0 and char_value < 128:  # Valid ASCII range
			result += char(char_value)
	
	return result

func _physics_process(delta: float) -> void:
	
	#box_spawner.disable = ul_1_3.speed == 0
	color_1 = OIPComms.read_int32(tag_group,hmi_start_color_1)
	color_2 = OIPComms.read_int32(tag_group,hmi_start_color_2)

	#print("Log String: ", read_string(tag_group, "UL1_3_JR_PB1.CTRL.STS.Log"))

	match color_1:
		1:
			display_color_1 = Color.CHOCOLATE
		2:
			display_color_1 = Color.GRAY
		3:
			display_color_1 = Color.GREEN
		4:
			display_color_1 = Color.BLACK
		_:
			display_color_1 = Color.WHITE
	match color_2:
		1:
			display_color_2 = Color.CHOCOLATE
		2:
			display_color_2 = Color.GRAY
		3:
			display_color_2 = Color.GREEN
		4:
			display_color_2 = Color.BLACK
		_:
			display_color_2 = Color.WHITE
	hmi_start_pb.button_color = display_color_1
	hmi_ul_1_3_jr_pb_2.button_color = display_color_2
	
