extends Node2D


onready var character = preload("res://GD_scene/character.tscn")
onready var gear = preload("res://GD_scene/gear.tscn")
onready var health = preload("res://GD_scene/health.tscn")
onready var spawner = preload("res://GD_scene/spawn.tscn")
onready var game_over = preload("res://GD_scene/game_over.tscn")

var spawn_time = 3

func start():
	player_func()
	gear_func()
	$timer/gear.start()
	$timer/health.start()
	$timer/spawner.start()
	$"UI".timer_start()
	pass


# warning-ignore:unused_argument
func _physics_process(delta):
	var over = game_over.instance()
	
	spawn_time = 3 - Global.level / 10
	if spawn_time < 0.1:
		spawn_time = 0.1
	$timer/spawner.set_wait_time(spawn_time)
	
	
	if Global.health > 3:
		Global.health = 3
	
	if Global.progress >= Global.level_progress:
		Global.level += 1
		$"UI".level_up()
		Global.progress = 10
		Global.level_progress = 100 * Global.level
	
	if Global.health <= 0:
		Global.game_over = true
		Global.health = 1
		$menu.add_child(over)
		$timer/gear.stop()
		$timer/health.stop()
		$timer/spawner.stop()
		$"UI".timer_stop()
	pass


func player_func():
	var player_spawn = character.instance()
	var random_x
	var random_y
	var x
	var y
	
	randomize()
	random_x = randi() % 12 + 1
	random_y = randi() % 6 + 1
	
	x = -15 + (150 * random_x)
	y = 70 + (150 * random_y)
	
	player_spawn.position = Vector2(x, y)
	$character.add_child(player_spawn)
	pass


func _on_spawner_timeout():
	var spawner_spawn = spawner.instance()
	var random_x
	var random_y
	var x
	var y
	
	randomize()
	random_x = randi() % 12 + 1
	random_y = randi() % 6 + 1
	
	x = -15 + (150 * random_x)
	y = 70 + (150 * random_y)
		
	spawner_spawn.position = Vector2(x, y)
	$spawn.add_child(spawner_spawn)
	pass


func _on_gear_timeout():
	gear_func()
	pass


func _on_health_timeout():
	var health_spawn = health.instance()
	var random_x
	var random_y
	var x
	var y
	
	if Global.health < 3:
		randomize()
		random_x = randi() % 12 + 1
		random_y = randi() % 6 + 1
		
		x = -15 + (150 * random_x)
		y = 70 + (150 * random_y)
		
		health_spawn.position = Vector2(x, y)
		$spawn.add_child(health_spawn)
	pass


func gear_func():
	var gear_spawn = gear.instance()
	var random_x
	var random_y
	var x
	var y
	
	randomize()
	random_x = randi() % 12 + 1
	random_y = randi() % 6 + 1
	
	x = -15 + (150 * random_x)
	y = 70 + (150 * random_y)
	
	gear_spawn.position = Vector2(x, y)
	$spawn.add_child(gear_spawn)
	pass
