@tool
extends Polygon2D
class_name SetPiece


# Declare member variables here. Examples:
# var a = 2
# var b = "text"


# Called when the node enters the scene tree for the first time.
func _ready():
	_update_polygon_from_resource()
	self.color.a = 0.25
	if Engine.is_editor_hint():
		self.color.a = 0.25
		notify_property_list_changed()
		pass
	else:
		pass
		# hide()
	pass # Replace with function body


func _update_polygon_from_resource() -> void:
	if points_resource and points_resource.points.size() > 0:
		polygon = points_resource.points

signal interacted
signal walked
signal looked
signal touched
signal talked
signal entered(lab)
signal exited(lab)

@export var label: String
@export var priority: int = 0
@export var points_resource: PolygonPointsResource:
	set(value):
		points_resource = value
		_update_polygon_from_resource()

func _input(event):
	if not Engine.is_editor_hint():
		if event is InputEventMouseButton and Input.is_action_just_released("interact"):
			# Check if a script is running that shouldn't be interrupted
			var script_builder = get_node_or_null("/root/Node2D/GameScript")
			if script_builder and script_builder.current_script and not script_builder.current_script.can_interrupt:
				return  # Let the script handle the input
			
			# Check if this is the top-priority hovered SetPiece
			var top_piece = ActionState.get_top_hovered_setpiece()
			if top_piece != self:
				return
			
			get_viewport().set_input_as_handled()
			
			# Check if interacted signal has connections - it takes precedence
			if interacted.get_connections().size() > 0:
				emit_signal("interacted")
				return
			
			# Otherwise, emit action-specific signal based on current cursor
			match ActionState.current_action:
				ActionState.Action.WALK:
					if walked.get_connections().size() > 0:
						emit_signal("walked")
				ActionState.Action.LOOK:
					if looked.get_connections().size() > 0:
						emit_signal("looked")
				ActionState.Action.TOUCH:
					if touched.get_connections().size() > 0:
						emit_signal("touched")
				ActionState.Action.TALK:
					if talked.get_connections().size() > 0:
						emit_signal("talked")
				ActionState.Action.ITEM:
					if InventoryManager.selected_item:
						var item_id = InventoryManager.selected_item
						var scene = get_node_or_null("/root/Node2D/SceneViewport/background")
						if scene and scene is Scene:
							scene._use_item_on_setpiece(item_id, self)
