extends VBoxContainer

signal changed
signal leave_stage

var has_stage:bool = false:
	set(stage):
		has_stage = stage
		if is_node_ready():
			%MusicPreview.playing = has_stage
			if has_stage:
				music_mute_switch.grab_focus()
		

var current_music_decay:float = 0

@onready var music_mute_switch: CheckBox = %MuteSoundtrack
@onready var sfx_mute_switch: CheckBox = %MuteSFX
@onready var music_slider: Range = %MusicSlider
@onready var sfx_slider: Range = %SoundSlider
@onready var speech_slider: Range = %SpeechSlider
@onready var sum_slider: Range = %SumSlider
@onready var text_lang_selector: OptionButton = %InterfaceSelector
@onready var speech_lang_selector: OptionButton = %SpeechSelector

func _process(delta: float) -> void:
	if current_music_decay > 0:
		current_music_decay -= delta
		if current_music_decay < 0:
			%MusicMixer.play("blend_out")
	

var has_changed: bool = false:
	set(value):
		has_changed = value

func _ready() -> void:
	update_ui_from_state()
	
	music_mute_switch.pressed.connect(func(value): State.music_muted = value)
	sfx_mute_switch.pressed.connect(func(value): State.music_muted = value)
	
	music_slider.value_changed.connect(
		func(value):
			State.music_volume = value
			current_music_decay = 2
			%MusicMixer.play("blend_in")
	)
	sfx_slider.value_changed.connect(func(value): State.sfx_volume = value)
	speech_slider.value_changed.connect(func(value): State.speech_volume = value)
	sum_slider.value_changed.connect(func(value): State.main_volume = value)
	
	changed.connect(func():has_changed = true)
	
	%ResetButton.pressed.connect(_on_reset_button_pressed)
	%SaveButton.pressed.connect(_on_exit_button_pressed)


func _on_reset_button_pressed():
	music_mute_switch.button_pressed = false
	sfx_mute_switch.button_pressed = false
	music_slider.value = 1
	sfx_slider.value = 1
	speech_slider.value = 1
	sum_slider.value = 1

func update_ui_from_state():
	music_mute_switch.button_pressed = State.sfx_muted
	sfx_mute_switch.button_pressed = State.music_muted
	music_slider.value = State.music_volume
	sfx_slider.value = State.sfx_volume
	speech_slider.value = State.speech_volume
	sum_slider.value = State.main_volume
	text_lang_selector.select(State.text_language)
	speech_lang_selector.select(State.speech_language)
	
func _on_exit_button_pressed() -> void:
	leave_stage.emit()
	State.save_settings()
	State.leave_stage(self)
