# UI operations module
# Handles: add_ui_control, set_ui_layout, add_ui_container
# Corresponds to: test_ui.py
class_name UIOps


## Add a UI control to a scene
static func add_ui_control(ctx: SceneTree, params: Dictionary) -> void:
	ctx.log_info("Adding UI control: " + params.control_name)

	var full_scene_path: String = params.scene_path
	if not full_scene_path.begins_with("res://"):
		full_scene_path = "res://" + full_scene_path

	if not FileAccess.file_exists(full_scene_path):
		ctx.log_error("Scene file does not exist: " + full_scene_path)
		ctx.quit(1)

	var scene: PackedScene = load(full_scene_path)
	if not scene:
		ctx.log_error("Failed to load scene: " + full_scene_path)
		ctx.quit(1)

	var scene_root: Node = scene.instantiate()

	# Find parent node
	var parent_node: Node = scene_root.get_node_or_null(NodePath(params.parent_node_path))
	if not parent_node:
		ctx.log_error("Parent node not found: " + params.parent_node_path)
		ctx.quit(1)

	# Create control
	var control: Node = ctx.instantiate_class(params.control_type)
	if not control:
		ctx.log_error("Failed to create control of type: " + params.control_type)
		ctx.quit(1)

	if not control is Control:
		ctx.log_error("Node type is not a Control: " + params.control_type)
		ctx.quit(1)

	control.name = params.control_name

	# Set text if provided and control supports it
	if params.has("text"):
		if control.has_method("set_text"):
			control.text = params.text

	# Add to scene
	parent_node.add_child(control)
	control.owner = scene_root

	if ctx.debug_mode:
		print("[DEBUG] UI control added to scene")

	# Save scene
	var packed_scene: PackedScene = PackedScene.new()
	var result: int = packed_scene.pack(scene_root)

	if result == OK:
		var save_error: int = ResourceSaver.save(packed_scene, full_scene_path)
		if save_error == OK:
			print("UI control '" + params.control_name + "' added successfully")
		else:
			ctx.log_error("Failed to save scene: " + str(save_error))
			ctx.quit(1)
	else:
		ctx.log_error("Failed to pack scene: " + str(result))
		ctx.quit(1)


## Set UI layout properties
static func set_ui_layout(ctx: SceneTree, params: Dictionary) -> void:
	ctx.log_info("Setting UI layout")

	var full_scene_path: String = params.scene_path
	if not full_scene_path.begins_with("res://"):
		full_scene_path = "res://" + full_scene_path

	if not FileAccess.file_exists(full_scene_path):
		ctx.log_error("Scene file does not exist: " + full_scene_path)
		ctx.quit(1)

	var scene: PackedScene = load(full_scene_path)
	if not scene:
		ctx.log_error("Failed to load scene: " + full_scene_path)
		ctx.quit(1)

	var scene_root: Node = scene.instantiate()

	# Find control node
	var control: Node = scene_root.get_node_or_null(NodePath(params.node_path))
	if not control:
		ctx.log_error("Node not found: " + params.node_path)
		ctx.quit(1)

	if not control is Control:
		ctx.log_error("Node is not a Control: " + params.node_path)
		ctx.quit(1)

	# Apply anchor preset if specified
	if params.has("anchor_preset"):
		var preset_name: String = params.anchor_preset
		var preset_value: int = _get_anchor_preset_value(preset_name)
		if preset_value >= 0:
			control.set_anchors_and_offsets_preset(preset_value)
		else:
			ctx.log_error("Invalid anchor preset: " + preset_name)
			ctx.quit(1)

	# Set position if specified
	if params.has("position"):
		var pos = _parse_vector2(params.position)
		if pos:
			control.position = pos

	# Set size if specified
	if params.has("size"):
		var sz = _parse_vector2(params.size)
		if sz:
			control.size = sz

	# Set custom anchors if specified
	if params.has("anchors"):
		var anchors_data: Dictionary = {}
		if typeof(params.anchors) == TYPE_STRING:
			var json: JSON = JSON.new()
			if json.parse(params.anchors) == OK:
				anchors_data = json.get_data()
		else:
			anchors_data = params.anchors

		if anchors_data.has("left"):
			control.anchor_left = anchors_data.left
		if anchors_data.has("top"):
			control.anchor_top = anchors_data.top
		if anchors_data.has("right"):
			control.anchor_right = anchors_data.right
		if anchors_data.has("bottom"):
			control.anchor_bottom = anchors_data.bottom

	if ctx.debug_mode:
		print("[DEBUG] UI layout set")

	# Save scene
	var packed_scene: PackedScene = PackedScene.new()
	var result: int = packed_scene.pack(scene_root)

	if result == OK:
		var save_error: int = ResourceSaver.save(packed_scene, full_scene_path)
		if save_error == OK:
			print("UI layout updated")
		else:
			ctx.log_error("Failed to save scene: " + str(save_error))
			ctx.quit(1)
	else:
		ctx.log_error("Failed to pack scene: " + str(result))
		ctx.quit(1)


## Add a UI container
static func add_ui_container(ctx: SceneTree, params: Dictionary) -> void:
	ctx.log_info("Adding UI container: " + params.container_name)

	var full_scene_path: String = params.scene_path
	if not full_scene_path.begins_with("res://"):
		full_scene_path = "res://" + full_scene_path

	if not FileAccess.file_exists(full_scene_path):
		ctx.log_error("Scene file does not exist: " + full_scene_path)
		ctx.quit(1)

	var scene: PackedScene = load(full_scene_path)
	if not scene:
		ctx.log_error("Failed to load scene: " + full_scene_path)
		ctx.quit(1)

	var scene_root: Node = scene.instantiate()

	# Find parent node
	var parent_node: Node = scene_root.get_node_or_null(NodePath(params.parent_node_path))
	if not parent_node:
		ctx.log_error("Parent node not found: " + params.parent_node_path)
		ctx.quit(1)

	# Create container
	var container: Node = ctx.instantiate_class(params.container_type)
	if not container:
		ctx.log_error("Failed to create container of type: " + params.container_type)
		ctx.quit(1)

	if not container is Container:
		ctx.log_error("Node type is not a Container: " + params.container_type)
		ctx.quit(1)

	container.name = params.container_name

	# Add to scene
	parent_node.add_child(container)
	container.owner = scene_root

	if ctx.debug_mode:
		print("[DEBUG] UI container added to scene")

	# Save scene
	var packed_scene: PackedScene = PackedScene.new()
	var result: int = packed_scene.pack(scene_root)

	if result == OK:
		var save_error: int = ResourceSaver.save(packed_scene, full_scene_path)
		if save_error == OK:
			print("UI container '" + params.container_name + "' added successfully")
		else:
			ctx.log_error("Failed to save scene: " + str(save_error))
			ctx.quit(1)
	else:
		ctx.log_error("Failed to pack scene: " + str(result))
		ctx.quit(1)


# Helper functions

static func _parse_vector2(data) -> Vector2:
	if typeof(data) == TYPE_STRING:
		var json: JSON = JSON.new()
		if json.parse(data) == OK:
			var arr: Array = json.get_data()
			if arr.size() >= 2:
				return Vector2(arr[0], arr[1])
	elif typeof(data) == TYPE_ARRAY and data.size() >= 2:
		return Vector2(data[0], data[1])
	return Vector2.ZERO


static func _get_anchor_preset_value(preset_name: String) -> int:
	match preset_name.to_upper():
		"TOPLEFT", "TOP_LEFT":
			return Control.PRESET_TOP_LEFT
		"TOPRIGHT", "TOP_RIGHT":
			return Control.PRESET_TOP_RIGHT
		"BOTTOMLEFT", "BOTTOM_LEFT":
			return Control.PRESET_BOTTOM_LEFT
		"BOTTOMRIGHT", "BOTTOM_RIGHT":
			return Control.PRESET_BOTTOM_RIGHT
		"CENTERLEFT", "CENTER_LEFT":
			return Control.PRESET_CENTER_LEFT
		"CENTERTOP", "CENTER_TOP":
			return Control.PRESET_CENTER_TOP
		"CENTERRIGHT", "CENTER_RIGHT":
			return Control.PRESET_CENTER_RIGHT
		"CENTERBOTTOM", "CENTER_BOTTOM":
			return Control.PRESET_CENTER_BOTTOM
		"CENTER":
			return Control.PRESET_CENTER
		"LEFTWIDE", "LEFT_WIDE":
			return Control.PRESET_LEFT_WIDE
		"TOPWIDE", "TOP_WIDE":
			return Control.PRESET_TOP_WIDE
		"RIGHTWIDE", "RIGHT_WIDE":
			return Control.PRESET_RIGHT_WIDE
		"BOTTOMWIDE", "BOTTOM_WIDE":
			return Control.PRESET_BOTTOM_WIDE
		"VCENTERWIDE", "VCENTER_WIDE":
			return Control.PRESET_VCENTER_WIDE
		"HCENTERWIDE", "HCENTER_WIDE":
			return Control.PRESET_HCENTER_WIDE
		"FULLRECT", "FULL_RECT":
			return Control.PRESET_FULL_RECT
		_:
			return -1
