extends Node

@export var mainPanel : Control
@export var choiceButtonsParent : Control
@export var joyMeter : TextureProgressBar
@export var sadnessMeter : TextureProgressBar

var mainPanelLabel : RichTextLabel
var choiceButtons : Array[ChoiceButton] 

@onready var dramaManager := DramaManager.new()

func _ready():
	StoryConfig.initialize()
	_update_meters(0, 0)

	var choiceSelected := func(button:ChoiceButton) -> void:
		_update_prompt(button.get_prompt_id(), button.get_id())
		_update_meters(button.get_joy_val(), button.get_sadness_val())

	for child in choiceButtonsParent.get_children():
		if child is ChoiceButton:
			choiceButtons.append(child)
			child.selected.connect(choiceSelected)
			continue
		push_warning("Non Choice Button node is child of choice buttons parent.")

	mainPanelLabel = mainPanel.get_node("RichTextLabel")
	_update_prompt(0, 0)

func _update_meters(jIncrease:int, sIncrease:int) -> void:
	dramaManager.joyVal += -jIncrease
	dramaManager.sadnessVal += -sIncrease
	joyMeter.value = dramaManager.joyVal
	sadnessMeter.value = dramaManager.sadnessVal

func _update_prompt(promptID:int, choiceID:int) -> void:

	# Unlock new choice based on choice selected
	var choice := StoryConfig.get_choice(choiceID)
	var unlockMap = choice.unlockMap
	var unlockPrompt = unlockMap.promptID
	var unlockChoice = unlockMap.choiceID
	if unlockPrompt != -1 and unlockChoice != -1:
		var newChoiceIDs = StoryConfig.get_prompt(unlockPrompt).choiceIDs.duplicate()
		newChoiceIDs.append(unlockChoice)
		StoryConfig.overwrite_prompt_choices(unlockPrompt, newChoiceIDs)

	var prompt := StoryConfig.get_prompt(promptID)
	mainPanelLabel.text = prompt.text
	var choiceIDs : Array[int] = prompt.choiceIDs

	var choiceCount := 0
	for i in range(prompt.choiceIDs.size()):
		if i >= choiceButtons.size():
			push_error("Unable to map all choices. Quantity exceeds button count: %s" % i)
			return
		choiceCount += 1

		var id := choiceIDs[i]
		var c := StoryConfig.get_choice(id)
		var button := choiceButtons[i]

		button.set_id(id)
		button.set_prompt_id(c.promptID)
		button.set_label_text(c.text)
		button.set_sadness_val(c.sadness)
		button.set_joy_val(c.joy)
		button.show()
		button.process_mode = Node.PROCESS_MODE_INHERIT

	for i in range(choiceButtons.size()):
		if i >= choiceCount:
			choiceButtons[i].hide()
			choiceButtons[i].process_mode = Node.PROCESS_MODE_DISABLED
