extends ProgressBar

class_name Score

@export var ScoreDecayTime : float = 1
@export var ScoreDecayValue : int = 1

@export var Points : Dictionary = {
	"Cannon" : 8.0,
	"Trampoline" : 3.0,
	"Ice": 20.0,
	"Death": 20.0,
	"Banana": 10.0,
	"SlideInto": 10.0,
	"ShotInto": 10.0,
	"SeesawFlip": 60.0,
}

const laughter_particles_scene: PackedScene = preload("res://mechanics/laughter/laughter_particles.tscn")

var SilentAudience : AudioStreamPlayer
var MediumAudience : AudioStreamPlayer
var LoudAudience : AudioStreamPlayer

var score : int = 0
var scoreDecayTimer = 0
var won = false
var neededPoints : int

func _ready():
	SilentAudience = get_node("SilentAudience")
	MediumAudience = get_node("MediumAudience")
	LoudAudience = get_node("LoudAudience")
	score = 0

func _process(delta):
	if won:
		return
	
	neededPoints = GameConstants.neededPoints
	scoreDecayTimer += delta
	if scoreDecayTimer > ScoreDecayTime:
		scoreDecayTimer = 0
		score = max(0, score-ScoreDecayValue)
	self.value = int((score*100)/neededPoints)
	
	if score >= neededPoints and !won:
		won = true
		(GameConstants.get_current_level() as Level).on_won()

func _on_score_event_happend(event : String):
	if not event in Points:
		push_error("Score Event " + event + " does not exist!")
		return
	var score_addition: int = Points[event]
	score += score_addition
	if score > neededPoints*0.7:
		if ! LoudAudience.playing:
			LoudAudience.play(0.6)
	elif score > neededPoints*0.4:
		if ! MediumAudience.playing:
			MediumAudience.play(0.55)
	else:
		if ! SilentAudience.playing:
			SilentAudience.play(1.35)
	
	var instance: Node = laughter_particles_scene.instantiate()
	self.add_child(instance)
	instance.activate(score_addition)

func _connect_clown(clown):
	clown.score_event.connect(_on_score_event_happend)
