class_name AdventurerProfileWindow extends ProfileWindow

var data : Adventurer
@onready var nameLabel = %NameLabel
@onready var jobLabel = %JobLabel
@onready var expLabel : Label = %ExpLabel
@onready var levelLabel :Label = %LevelLabel
@onready var lifeLabel :Label = %LifeLabel
@onready var energyLabel :Label = %EnergyLabel

@onready var strLabel :Label = %STRLabel
@onready var dexLabel :Label = %DEXLabel
@onready var intLabel :Label = %INTLabel
@onready var chaLabel :Label = %CHALabel
@onready var faiLabel :Label = %FAILabel
@onready var lukLabel :Label = %LUKLabel

var item_slots : Array[ItemSlot]

var item_display_window_template = preload("res://templates/item_display_window.tscn")

func setup(adv : Adventurer) -> void:
	data = adv
	data.changed.connect(_on_data_changed)
	update_stats()
	item_slots = []
	for child : ItemSlot in %InventoryGrid.get_children():
		item_slots.append(child)
		child.display_item.connect(_on_display_item)
	if data.job:
		var portrait : AdventurerPortrait = data.job.portrait.instantiate()
		%PortraitFrame.add_child(portrait)
		portrait.scale = Vector2(.6,.6)
		portrait.set_appearance(data.appearance)
	#TODO: Show equipment
	update_items()

func update_stats() -> void:
	nameLabel.text = data.full_name()
	if data.job:
		jobLabel.text = data.job.name
	else:
		jobLabel.text = "ERROR"
	levelLabel.text = str(data.level)
	expLabel.text = "Exp: %d/%d" % [data.exp, data.get_tnl()]
	lifeLabel.text = "Life: " + str(data.life) + "/" + str(data.max_life)
	energyLabel.text = "Energy: " + str(data.energy) + "/" + str(data.max_energy)
	strLabel.text = str(data.stats.STR)
	dexLabel.text = str(data.stats.DEX)
	intLabel.text = str(data.stats.INT)
	chaLabel.text = str(data.stats.CHA)
	faiLabel.text = str(data.stats.FAI)
	lukLabel.text = str(data.stats.LUK)

func update_items() -> void:
	var isize = data.inventory_size.x * data.inventory_size.y
	var islots = len(item_slots)
	%InventoryGrid.columns = data.inventory_size.x
	for crd in data.inventory.keys():
		var idx = crd.y * data.inventory_size.x + crd.x
		var item = data.inventory[crd]
		item_slots[idx].update(item)
		item_slots[idx].visible = true
	
	for idx in range(isize, islots):
		item_slots[idx].visible = false


func _on_data_changed() -> void:
	update_stats()
	update_items()

func _on_display_item(item : Item) -> void:
	var wnd : Popup = item_display_window_template.instantiate()
	adding_subwindow = true
	add_child(wnd)
	wnd.setup(item)
	wnd.popup_centered()
	adding_subwindow = false
