extends Node2D

onready var layers = [$L0, $L1, $L2, $L3]
onready var kick = $Kick
onready var rain = $Rain
onready var fade_in = $FadeIn

var layer_count = 1
var combat_intensity = 0.0
var inside = false

const fade_in_base = -30.0

func _ready():
	#test
	#go_inside()
#	layers[0].set_stream(preload("res://music/ld51-0.ogg"))
#	layers[0].play()

	rain.play()
	
func music_start():
	layers[0].play()
	
#test
#var debug_int = 0.0
#func _input(event):
#	if event is InputEventKey and event.pressed:
#		if event.is_action_pressed("move_up"):
#			increase_intensity()
#		if event.is_action_pressed("fast_forward"):
#			decrease_intensity()
#		if event.is_action_pressed("move_left"):
#			debug_int -= 0.1
#			set_combat_intensity(debug_int)
#		if event.is_action_pressed("move_right"):
#			debug_int += 0.1
#			set_combat_intensity(debug_int)
#		print(debug_int)
	
func _process(_delta: float):
	if !fade_in.is_stopped():
		layers[layer_count - 1].set_volume_db(fade_in_base * fade_in.time_left)

func update():
	var l0position = layers[0].get_playback_position()
	for i in range(1, layer_count):
		if !layers[i].playing:
			layers[i].play()
			layers[i].seek(l0position)
			layers[i].set_volume_db(fade_in_base)
	for i in range(layer_count, layers.size()):
		layers[i].stop()
		
	if combat_intensity < 0.01:
		kick.stop()
	else:
		kick.set_volume_db(-45.0 + combat_intensity / 2.0)
		if !kick.playing:
			kick.play()
			kick.seek(l0position)
		kick.set_volume_db(-45.0 + combat_intensity * 50.0)
	
	var fx = AudioServer.get_bus_effect(AudioServer.get_bus_index("Music"), 0)
	
	if fx:
		if combat_intensity < 0.01:
			fx.cutoff_hz = 20500
		elif combat_intensity < 0.4:
			fx.cutoff_hz = 3000 - (combat_intensity - 0.4) * 2500
		elif combat_intensity < 0.8:
			fx.cutoff_hz = 1000 - (combat_intensity - 0.8) * 3000
		else:
			fx.cutoff_hz = 400

func increase_intensity():
	layer_count += 1
	if layer_count > layers.size():
		layer_count = layers.size()
	else:
		fade_in.start()
	update()

func decrease_intensity():
	layer_count -= 1
	if layer_count < 1:
		layer_count = 1
	update()

func go_inside():
	inside = true
	if rain:
		rain.set_stream(preload("res://music/rain_inside.ogg"))
		rain.play()
		set_rain_intensity(0.0)

func set_rain_intensity(var intensity: float):
	if inside:
		rain.set_volume_db(-20.0 + intensity)

func set_combat_intensity(var intensity: float):
	combat_intensity = intensity
	update()

func _on_L0_finished():
	if layers.size() > 0:
		layers[0].set_stream(preload("res://music/ld51-0.ogg"))
		layers[0].play()

func _on_FadeIn_timeout():
	layers[layer_count - 1].set_volume_db(0.0)
