# Hurry Curry! - a game about cooking
# Copyright (C) 2025 Hurry Curry! contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
extends Node

@onready var click_sound = $UI/Click
@onready var hover_sound = $UI/Hover
@onready var game_start_sound = $UI/GameStart
@onready var music_node : Node = $Music

var item_sounds: Dictionary = {}
var item_id: int = 0
var current_music_player: AudioStreamPlayer
var current_music_filename = ""
var volume_target = 0.
var dampen_target = 0.
var dampen_value = 0.

const VOLUME_MIN = -30.
const FADE_SPEED = 20.
const EFFECT_FADE_SPEED = 0.5

func set_music(filename, volume = 0., dampen = false):
	if current_music_filename != filename:
		if filename == null:
			current_music_filename = null
			current_music_player = null
		else:
			var player = AudioStreamPlayer.new()
			player.stream = load("res://audio/music/%s.ogg" % filename)
			player.volume_db = VOLUME_MIN + 1.
			player.autoplay = true
			player.name = filename
			player.bus = "Music"
			current_music_player = player
			current_music_filename = filename
			$Music.add_child(player)

	volume_target = volume
	dampen_target = 1. if dampen else 0.

func _process(dt: float):
	for c in $Music.get_children():
		if c is AudioStreamPlayer:
			if c == current_music_player:
				if c.volume_db > volume_target: c.volume_db = max(volume_target, c.volume_db - dt * FADE_SPEED)
				else: c.volume_db = min(volume_target, c.volume_db + dt * FADE_SPEED)
			else:
				c.volume_db -= dt * FADE_SPEED
				if c.volume_db <= VOLUME_MIN: c.queue_free()

	var prev_dampen = dampen_value
	dampen_value = G.interpolate_linear(dampen_value, dampen_target, dt * EFFECT_FADE_SPEED)
	AudioServer.set_bus_effect_enabled(1, 0, dampen_value > 0.)
	AudioServer.set_bus_effect_enabled(1, 1, dampen_value > 0.)
	if dampen_value != prev_dampen:
		var lowpass = AudioServer.get_bus_effect(1, 0) as AudioEffectFilter
		var reverb = AudioServer.get_bus_effect(1, 1) as AudioEffectReverb
		lowpass.cutoff_hz = lerp(3200., 400., pow(dampen_value, 8.))
		reverb.wet = dampen_value * 0.5

func set_volume(bus: int, value: float):
	AudioServer.set_bus_volume_db(bus, value)
	if value == -30: AudioServer.set_bus_mute(bus, true)
	else: AudioServer.set_bus_mute(bus, false)

func play_click():
	click_sound.play()

func play_hover():
	hover_sound.play()

func play_game_start():
	game_start_sound.play()

func play_hover_maybe(element):
	# Don't play hover sound when focus is changed by clicking using a mouse.
	# TODO: Clean up this code and find a proper solution.
	if element is Button:
		if element.is_hovered():
			return
	play_hover()

func item_progress(item: Item, running: AudioStream, stopping: AudioStream, volume=0.) -> int:
	item_id += 1
	var running_player: AudioStreamPlayer3D = AudioStreamPlayer3D.new()
	running_player.stream = running
	running_player.name = "Running%d" % item_id
	running_player.volume_db = volume
	add_child(running_player)
	var stopping_player: AudioStreamPlayer3D = AudioStreamPlayer3D.new()
	stopping_player.stream = stopping
	stopping_player.name = "Stopping%d" % item_id
	stopping_player.volume_db = volume
	running_player.play()
	add_child(stopping_player)
	item_sounds[item_id] = [item, running_player, stopping_player, false]
	return item_id

func item_finished(id: int):
	var running_player: AudioStreamPlayer3D = item_sounds[id][1]
	var stopping_player: AudioStreamPlayer3D = item_sounds[id][2]
	item_sounds[id][3] = true
	running_player.stop()
	stopping_player.play()
	stopping_player.finished.connect(func():
		free_sound(id)
	)

func free_sound(id: int):
	var running_player: AudioStreamPlayer3D = item_sounds[id][1]
	var stopping_player: AudioStreamPlayer3D = item_sounds[id][2]
	running_player.queue_free()
	stopping_player.queue_free()
	item_sounds.erase(id)

func _physics_process(_delta):
	for k in item_sounds.keys():
		if item_sounds[k][0] != null:
			var position: Vector3 = item_sounds[k][0].position
			item_sounds[k][1].position = position
			item_sounds[k][2].position = position
		elif not item_sounds[k][3]:
			item_finished(k)
