extends Node

const character_scene = preload("res://scenes/character.tscn")
onready var player = $Guys/Player
		
var game_over = false
var game_start = 0
		  	
var bot_styles = [
			{"nickname": "Hex[man]",   "skin": "ffffff", "helment": "b07d01", "armor": "c11a1a"},
			{"nickname": "Darthman",   "skin": "261b31", "helment": "21a7a7", "armor": "0f5414"}, 
			{"nickname": "Mefistofel", "skin": "ffbf94", "helment": "3e1900", "armor": "5c2806"},	
 			{"nickname": "KEFIR",      "skin": "f7dbc8", "helment": "ff004f", "armor": "ffffff"},	
			{"nickname": "Neuch",      "skin": "f29db7", "helment": "ff2200", "armor": "ff004f"},	
			{"nickname": "ZblCoder",   "skin": "9a9a9a", "helment": "691d1d", "armor": "610e0e"},
			{"nickname": "cherepets",  "skin": "51ce34", "helment": "275e1a", "armor": "275e1a"},
			{"nickname": "John Doe",   "skin": "a1bff0", "helment": "000000", "armor": "001b6b"},
			{"nickname": "Yakroot",    "skin": "def774", "helment": "ff0000", "armor": "a500a0"}
		   ]

func _ready():
	randomize()
	var level = load("res://scenes/levels/level0" + str(global.level) + ".tscn")
	var level_node = level.instance()

	$Level.add_child(level_node)
	game_start = OS.get_ticks_msec()
	
	global.shots_node = $Shots
	global.particles_node = $Particles
	
	player.set_properties(1, global.player_nickname)
	
	var i = 0
	for style in bot_styles:
		if player.nickname.nocasecmp_to(style.nickname) == 0:
			player.set_style(style)
			bot_styles.remove(i)
			break
		
		i += 1
	
	for i in global.bot_amount:
		var x = round(rand_range(0, bot_styles.size() - 1))
		var style = bot_styles[x]
		var bot = character_scene.instance()
		bot.set_properties(i + 2, style.nickname)
		bot.set_style(style)
		bot_styles.remove(x)
		$Guys.add_child(bot)
			
	for guy in $Guys.get_children():
		guy.connect("on_kill", self, "_on_kill")
		
	var spawns = level_node.get_node("Spawns")
	global.make_spawns(spawns)
	
	$GUI.reset()
	update_scoreboard()

func _input(event):
	if !game_over and event.is_action("shot") and !event.pressed:
		player.target = event.position
		player.fire()
		
func _process(delta):
	if Input.is_action_just_released("quit"):
		$GUI/QuitDialog.show()
		get_tree().paused = true
		
	if Input.is_action_just_pressed("score_board"):
		$GUI/Scoreboard.show()
	
	if Input.is_action_just_released("score_board"):
		$GUI/Scoreboard.hide()
			
	if player.spawn_state == player.SPAWN_FINISH:
		if Input.is_action_pressed("ui_right"):
			player.move_right()
		elif Input.is_action_pressed("ui_left"):
			player.move_left()
		else:
			player.idle()
	
		if Input.is_action_pressed("ui_up"):
			player.jump(player.MAX_JUMP_TIME)
	
	if game_over: 
		return
	
	if OS.get_ticks_msec() - game_start >= global.time_limit * 60000:
		game_over()
		return
	
	var guys = $Guys.get_children()
	
	for guy in guys:
		if guy.is_bot and guy.can_shoot():
			guy.target = null
			var distance = INF
			
			for opponent in guys:
				if guy != opponent:
					var d = (guy.position - opponent.position).length()
					
					if distance > d and guy.intersect_ray(opponent):
						distance = d
						guy.target = opponent.position
			
			guy.fire()
					

func sort_scores(a, b):
	if a.kills > b.kills:
		return true
	
	return false

func update_scoreboard():
	var data = []
	
	for guy in $Guys.get_children():
		data.push_back({"nickname": guy.nickname, "kills": guy.kills, "deaths": guy.deaths})
	
	data.sort_custom(self, "sort_scores")
	$GUI/Scoreboard.load_data(data)
	return data[0].nickname

func game_over():
	game_over = true
	$GUI.game_over(update_scoreboard())
	$GUI/Scoreboard.show()

func _on_Player_on_health_change(value):
	$GUI/Top/Health.value = value

func _on_kill(who, whom, headshot, weapon_name):
	update_scoreboard()
	$GUI.kills_log_write(who, whom, headshot, weapon_name)
	
	if who.kills == global.frags_limit:
		game_over()

func _on_QuitDialog_confirmed():
	get_tree().change_scene("res://scenes/main-menu.tscn")

func _on_QuitDialog_hide():
	get_tree().paused = false

func _on_Player_change_weapon(weapon_name, shot_count):
	match weapon_name:
		"Knife":
			$GUI/Top/Weapon.frame = 0 # need move to GUI script
			$GUI/Top/Shots.text = ""
		
		"Axe":
			$GUI/Top/Weapon.frame = 1
			$GUI/Top/Shots.text = str(shot_count)

func _on_Player_shoot(shot_count):
	$GUI/Top/Shots.text = str(shot_count)
