class_name GameController extends Node2D

# Game Data
var totalCrates = 4
var cratesDestroyed = 0
var coinsCollected =0
var totalCoinsAvailable = 0

var enemies = 0
var enemiesDict = {}

signal destroySignal(body)
signal levelCompleteSignal(level)
signal playerHurtSignal(healthRemaining)
signal playerKillSignal
signal timeCountSignal(timeRemaining, timeAvailable)
signal coinCountSignal(collected, available)

#level info
var timer:= Timer.new()
var levels = ["res://scenes/game.tscn","res://scenes/level2.tscn","res://scenes/level3.tscn"]
var soundtracks = ["res://assets/audio/music/CrashingOut.ogg","res://assets/audio/music/DragAndDreadTheme.ogg"]
var timers = [20,15,25]
var currentLevel = 0
var countdown=0

var player:Resource
var slime:Resource

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	player = load("res://scripts/res/playerStats.tres")
	slime = load("res://scripts/res/slimeStats.tres")
	
	countdown = timers[currentLevel]
	add_child(timer)
	timer.wait_time = 1
	timer.one_shot = false
	timer.connect("timeout", secondCounter)
	timer.start()
func reset():
	countdown = timers[currentLevel]
	player.health = player.max_health
	coinsCollected = 0
	
func secondCounter():
	countdown -=1
	timeCountSignal.emit(countdown, timers[currentLevel])
	
	if countdown <=0:
		
		levelCompleteSignal.emit(levels[currentLevel])

func _on_trigger_area_trigger(effect, body) -> void:
	match effect:
		"destroy":
			#write code to destroy
			if body is Crate:
				destroySignal.emit(body)
				cratesDestroyed +=1
		"powerup":
			if body is Player:
				pass

func bulletHit(body):
	if body is Crate:
		totalCrates -=1
		destroySignal.emit(body)
		if totalCrates <=0:
			#player wins
			currentLevel +=1
			if currentLevel >= levels.size():
				currentLevel = 0
			levelCompleteSignal.emit(levels[currentLevel])
	if body is Slime:
		#reduce health of slime
		enemiesDict[body]["health"] -=30
		if enemiesDict[body]["health"] <=0:
			#killed the slime
			destroySignal.emit(body)
		
func numberOfCrates(value):
	totalCrates = value
	
func numberOfCoins(value):
	totalCoinsAvailable = value
	
func numberOfBadguys(value):
	enemies = value
func addEnemyToLevel(enemy):
	#assign a health using the enemy as a key
	var enemyStat = {
		"health": slime.health,
		"damage": slime.meleeDamage
	}
	enemiesDict[enemy] = enemyStat
	
func coinCollected(body, coin):
	
	if body is Player:
		#increase coins collected count
		coinsCollected +=1
		coinCountSignal.emit(coinsCollected, totalCoinsAvailable)
		destroySignal.emit(coin)
func playerDamage(body, badguy):
	if body is Player:
		player.health -= enemiesDict[badguy]["damage"]
		if player.health > 0:
			playerHurtSignal.emit(player.health, player.max_health)
		else:
			#stop the timer!
			timer.stop()
			playerKillSignal.emit()
			
func playerDeathComplete():
	levelCompleteSignal.emit(levels[currentLevel])
