@tool
extends PanelContainer

@onready var vbc_spawn_slot_root: VBoxContainer = %VBC_SpawnSlotRoot

@onready var b_insert: Button = %B_Insert
@onready var b_remove: Button = %B_Remove
@onready var b_add: Button = %B_Add

@onready var rtl_context: RichTextLabel = %RTL_Context

const DEFAULT_CONTEXT: Dictionary = {
	"default": "Press insert to generate a act.",
	"removerr": "Act need at least on single act.",
	"adderr": "Single act count cannot over the count of props.",
	"inserterr": "Insert act with empty slot."
}

var _inited: bool = false
var _max_length: int = -1

var _cached_prop_id: Array[int]

## 默认的Slot
const SLOT: PackedScene = preload("res://addons/reedscene/act/StateDrapSlot.tscn")

func _ready() -> void:
	if not Engine.is_editor_hint():
		return

	# 连接按钮
	b_add.pressed.connect(_on_add_pressed)
	b_remove.pressed.connect(_on_remove_pressed)
	b_insert.pressed.connect(_on_insert_pressed)

	# 初始保证至少有一个 Slot
	if vbc_spawn_slot_root.get_child_count() == 0:
		_add_slot()

	_update_b_remove_state()

func init(info:Dictionary) -> void:
	_inited = true
	if info.has("size"):
		self._max_length = info.get("size") as int

func _on_add_pressed() -> void:
	_add_slot()

func _on_remove_pressed() -> void:
	_remove_slot()

func _on_insert_pressed() -> void:
	_insert_act()

## 插入一個根據當前的條目生成的Act
func _insert_act()-> void:
	var slots = vbc_spawn_slot_root.get_children()
	for s in slots:
		var vs = s as StateDrapSlot
		if not vs:
			continue ##後續要有報錯Message
		
		

## 添加一個Slot，不能超過當前Scene的最大prop數量
func _add_slot() -> void:
	if vbc_spawn_slot_root.get_child_count() >= _max_length:
		return
	
	var slot := SLOT.instantiate()
	slot.prop_info_cached.connect(_on_slot_prop_cached)
	vbc_spawn_slot_root.add_child(slot)
	slot.owner = get_tree().edited_scene_root # 编辑器可保存
	slot.init(vbc_spawn_slot_root.get_children().size())

	_update_b_remove_state()

func _on_slot_prop_cached(info:Dictionary,slot:StateDrapSlot) -> void:
	if not info.has("prop_id"):
		return
	
	var id : int = info.prop_id
	if _cached_prop_id.has(id):
		slot._set_state(0)
	else:
		_cached_prop_id.append(id)

## 移除一個Slot，最少不能為0
func _remove_slot() -> void:
	var count := vbc_spawn_slot_root.get_child_count()
	if count <= 1:
		return

	var last := vbc_spawn_slot_root.get_child(count - 1)
	last.queue_free()

	_update_b_remove_state()


func _update_b_remove_state() -> void:
	b_remove.disabled = vbc_spawn_slot_root.get_child_count() <= 1
