extends "res://scripts/Level.gd"

var stomp_timer = null
var speed_timer = null
var survived_timer = null
var start_running_timer = null
var trauma_strength = 0.5

var last_rand = 0

var timer = 0

var max_blocks = 17
var actual_block = 0
var automatic_speed = 250

var leaving_scene = false

var platform_blocks = []

var difficult = {
	"Easy": 1,
	"Medium": 1.2,
	"Hard": 1.25,
	"Very Hard": 1.4,
	"Supreme": 1.75,
	"Expert": 1.75
}

var fps = 60
var game_stop = false

func start_right_foot_movement():
	$GiantFeet/AnimatedRightFoot.play("Movement")
	pass


func load_feet_sprite():
	$GiantFeet/LeftFoot/Sole.animation_player = $GiantFeet/AnimatedLeftFoot
	$GiantFeet/RightFoot/Sole.animation_player = $GiantFeet/AnimatedRightFoot
	$GiantFeet/AnimatedLeftFoot.play("Movement")
	
	$GiantFeet/LeftFoot/stomp.hide()
	$GiantFeet/RightFoot/stomp.hide()
	
	var texture = null
	
	if DLC.has_file(Game.character, "/character/feet/leftfoot1.png"):
		texture = DLC.load_texture(Game.character, "/character/feet/leftfoot1.png")
		if texture:
			$GiantFeet/LeftFoot.frames.clear("ground")
			$GiantFeet/LeftFoot.frames.add_frame("ground", texture)
	
	if DLC.has_file(Game.character, "/character/feet/leftfoot2.png"):
		texture = DLC.load_texture(Game.character, "/character/feet/leftfoot2.png")
		if texture:
			$GiantFeet/LeftFoot.frames.clear("default")
			$GiantFeet/LeftFoot.frames.add_frame("default", texture)
	
	if DLC.has_file(Game.character, "/character/feet/rightfoot1.png"):
		texture = DLC.load_texture(Game.character, "/character/feet/rightfoot1.png")
		if texture:
			$GiantFeet/RightFoot.frames.clear("ground")
			$GiantFeet/RightFoot.frames.add_frame("ground", texture)
	
	if DLC.has_file(Game.character, "/character/feet/rightfoot2.png"):
		texture = DLC.load_texture(Game.character, "/character/feet/rightfoot2.png")
		if texture:
			$GiantFeet/RightFoot.frames.clear("default")
			$GiantFeet/RightFoot.frames.add_frame("default", texture)
	
	Utils.execute_after(self, "start_right_foot_movement", 2.0)
	
# warning-ignore:return_value_discarded
	$GiantFeet/LeftFoot/Sole.connect("stomp", self, "stomp_character")
# warning-ignore:return_value_discarded
	$GiantFeet/RightFoot/Sole.connect("stomp", self, "stomp_character")
	

func stomp_character():
	Game.stomped = true
	$GiantFeet/LeftFoot/Sole.disconnect("stomp", self, "stomp_character")
	$GiantFeet/RightFoot/Sole.disconnect("stomp", self, "stomp_character")
	
	$Player.can_move = false
	$Player.can_control = false
	$Player.hide()
	
	$GiantFeet/LeftFoot/stomp.show()
	$GiantFeet/RightFoot/stomp.show()
	
	Audio.play_sfx("stomp_hit")
	game_stop = true
	Utils.interpolate($Camera, "automatic_camera_movement", $Camera.automatic_camera_movement, 0, 0.4)
	if Game.effects: 
		Game.effects.fade_in_black(0.35)
	Utils.execute_after(self, "game_over", 0.4)
	Game.game_speed = 0.4
	Audio.fade_out(0.25)

# Called when the node enters the scene tree for the first time.
func _ready():
	
	Game.stomped = false
	leaving_scene = false
	
	$Player/PlayerHarm.hide()
	$GiantFeet.show()
	$Camera.show()
	
	if OS.get_name() == "Android":
		Controller.touchpad.show()
	
	can_pause = false
	
	stomp_timer = Timer.new()
	stomp_timer.connect("timeout", self, "stomp_timer_shake")
	stomp_timer.set_wait_time(2.0)
	stomp_timer.pause_mode = Node.PAUSE_MODE_STOP
	stomp_timer.set_one_shot(false) # Make sure it loops
	add_child(stomp_timer)
	stomp_timer.start()
	
	$Player.can_control = false
	
	$Camera/GUI/Pause.hide()
	get_tree().paused = false
	
	Utils.fade_out($Camera/GUI, 0.05)
	
	$Camera.verticalBoundary = Vector2(-860,640)
	if DLC.is_vertical_camera_limited(Game.character):
		$Camera.verticalBoundary = Vector2(0,640)
	
	
	survived_timer = Timer.new()
	survived_timer.connect("timeout", self, "survival_timer_shake")
	survived_timer.set_wait_time(1.0)
	survived_timer.pause_mode = Node.PAUSE_MODE_STOP
	survived_timer.set_one_shot(false) # Make sure it loops
	add_child(survived_timer)
	
	start_running_timer = Timer.new()
	start_running_timer.connect("timeout", self, "start_running_timer")
	start_running_timer.set_wait_time(2.0)
	start_running_timer.pause_mode = Node.PAUSE_MODE_STOP
	start_running_timer.set_one_shot(true) # Do not loop!
	add_child(start_running_timer)
	start_running_timer.start()
	
	speed_timer = Timer.new()
	speed_timer.connect("timeout", self, "speed_timer_increase")
	speed_timer.set_wait_time(30.0)
	speed_timer.pause_mode = Node.PAUSE_MODE_STOP
	speed_timer.set_one_shot(false) # Make sure it loops
	add_child(speed_timer)
	
	$Camera/Card/card.texture = Utils.load_file("res://@content/" + Game.character + "/card.png" )
	$Camera/Card/difficult.text = "Difficult: " + DLC.get_content_difficult(Game.character)
	$Camera/Card/character.text = "Character: " + DLC.get_content_character(Game.character)
	
	self.max_blocks = DLC.get_content_platform_count(Game.character)
	
	var platform_resource = Utils.load_file("res://@content/" + Game.character + "/platform/Platform01.tscn")
	var platform_scene = platform_resource.instance();
	platform_scene.pause_mode = Node.PAUSE_MODE_STOP
	
	var platform_image = "res://@content/" + Game.character + "/artworks/"+platform_scene.name.to_lower()+".png" 
	if Utils.file_exist(platform_image):
		platform_scene.get_node("Sprite").texture = Utils.load_file(platform_image)
		
	$Platform.call_deferred("add_child", platform_scene)
	
	var parallax_resource = Utils.load_file("res://@content/" + Game.character + "/parallax/Parallax.tscn")
	var parallax_scene = parallax_resource.instance();
	$Background.call_deferred("add_child", parallax_scene)
	
	$Camera/GUI/Timer.text = Utils.seconds_to_timer(0)
	
	if DLC.is_snowing(Game.character): Game.effects.start_snow()
	else:  Game.effects.stop_snow()
	if DLC.is_raining(Game.character): Game.effects.start_rain()
	else:  Game.effects.stop_rain()
	if DLC.is_fog(Game.character): Game.effects.start_lightfog()
	else:  Game.effects.stop_lightfog()
	if DLC.is_lavarock(Game.character): Game.effects.is_lavarock = true
	else:  Game.effects.is_lavarock = false
	
	load_feet_sprite()
	instantiate_blocks()
	
	# warning-ignore:return_value_discarded
	Controller.connect("controller_enter", self, "pause_game")
	
	# warning-ignore:return_value_discarded
	Controller.connect("controller_escape", self, "leave_level")
	
	Audio.play_ost("res://@content/" + Game.character + "/music.ogg")
	Audio.volume(80)
	
	self.trauma_strength = DLC.get_trauma_strength(Game.character)
	
func leave_level():
	if get_tree().paused:
		update_hiscore()
		MemoryCard.add_coins(Game.coins)
		Controller.disconnect("controller_enter", self, "pause_game")
		Controller.disconnect("controller_escape", self, "leave_level")
		game_stop = true
		Utils.interpolate($Camera, "automatic_camera_movement", $Camera.automatic_camera_movement, 0, 0.4)
		Game.coins = 0
		if Game.effects: 
			Game.effects.fade_in_black(0.5)
		Utils.execute_after(self, "back_to_menu", 0.55)
		Audio.fade_out(0.5)
	else:
		pause_game()


func back_to_menu():
	Game.load_level(0)


func pause_game():
	if not can_pause:
		return
	if not get_tree().paused:
		Audio.volume(60)
		$Camera/GUI/Pause.show()
		Game.effects.is_lavarock = false
		get_tree().paused = true
	else:
		Audio.volume(80)
		$Camera/GUI/Pause.hide()
		if DLC.is_lavarock(Game.character): Game.effects.is_lavarock = true
		else:  Game.effects.is_lavarock = false
		get_tree().paused = false


# warning-ignore:function_conflicts_variable
func start_running_timer():
	#if difficult.has(DLC.get_content_difficult(Game.character)):
	$Camera.automatic_camera_movement = self.automatic_speed * float(self.difficult[DLC.get_content_difficult(Game.character)])
	#else:
	#	$Camera.automatic_camera_movement = self.automatic_speed
	
	Utils.fade_in($Camera/GUI, 0.4)
	Utils.fade_out($Camera/Card, 0.6)
	$Player.can_control = true
	speed_timer.start()
	survived_timer.start()
	start_running_timer.disconnect("timeout", self, "start_running_timer")
	start_running_timer.queue_free()
	can_pause = true


func stomp_timer_shake():
	$Camera.add_trauma(trauma_strength)
	if DLC.has_file(Game.character, "/stomp.ogg"):
		Audio.play_sfx("res://@content/" + Game.character + "/stomp.ogg")
	else:
		Audio.play_sfx("stomp")
	pass

func survival_timer_shake():
	timer = timer + 1
	
	$Camera/GUI/Timer.text = Utils.seconds_to_timer(timer)

func speed_timer_increase():
	#if the camera automatic speed goes under 250 (its minimum speed) and it's not paused, it means the game has stopped.
	if $Camera.automatic_camera_movement < 100 and not paused:
		remove_child(speed_timer)
		speed_timer.disconnect("timeout", self, "speed_timer_increase")
		speed_timer.queue_free()
		return
	
	#but if the game's still going on, but it's paused, don't increase it.
	if paused: return
		
	self.automatic_speed = self.automatic_speed + 50
	if self.automatic_speed > 800: self.automatic_speed = 800
	$Camera.automatic_camera_movement = self.automatic_speed


func instantiate_blocks():
	var count = 2
	var next = ""
	while count < max_blocks + 1:
		if count < 10: next = "0" + str(count)
		else: next = str(count)
		var platform_resource = Utils.load_file("res://@content/" + Game.character + "/platform/Platform" + next + ".tscn")
		var platform_scene = platform_resource.instance();

		platform_blocks.append(platform_scene)
		count = count + 1



# Reset the internal randomizer, select a random object from the list
func load_next_block():
	randomize()
	actual_block = actual_block + 1
	
	var platform_scene = platform_blocks[randi() % platform_blocks.size()].duplicate()

	platform_scene.position = Vector2(actual_block * 1600, 0)
	$Platform.call_deferred("add_child", platform_scene)



# warning-ignore:unused_argument
func _physics_process(delta):
	if leaving_scene: return
	$GiantFeet.position.x = $Camera.position.x - 750
	
	get_node("Camera/GUI/Coins").text = str(Game.coins)
	
	$Camera/GUI/Position.position.x = $Player.position.x - $Camera.position.x
	if $Player.position.y + 360 < $Camera.position.y:
		$Camera/GUI/Position.show()
	else:
		$Camera/GUI/Position.hide()
	
	if $Player.position.x < $Camera.position.x - 710 and not game_stop:
		game_stop = true
		
		$GiantFeet/LeftFoot/Sole.disconnect("stomp", self, "stomp_character")
		$GiantFeet/RightFoot/Sole.disconnect("stomp", self, "stomp_character")
		Utils.interpolate($Camera, "automatic_camera_movement", $Camera.automatic_camera_movement, 0, 0.7)
		if Game.effects: 
			Game.effects.fade_in_black(0.6)
		Utils.execute_after(self, "game_over", 0.7)
		Audio.fade_out(0.5)
	
	if $Player.position.y > 800 and not game_stop:
		game_stop = true
		$GiantFeet/LeftFoot/Sole.disconnect("stomp", self, "stomp_character")
		$GiantFeet/RightFoot/Sole.disconnect("stomp", self, "stomp_character")
		Utils.interpolate($Camera, "automatic_camera_movement", $Camera.automatic_camera_movement, 0, 0.7)
		if Game.effects: 
			Game.effects.fade_in_black(0.6)
		Utils.execute_after(self, "game_over", 0.7)
		Audio.fade_out(0.5)
	
	if game_stop:
		$Player.can_control = false
	
	if Game.player_harm:
		Game.player_harm = false
		if $GiantFeet/LeftFoot/Sole:
			$GiantFeet/LeftFoot/Sole.disconnect("stomp", self, "stomp_character")
		if $GiantFeet/RightFoot/Sole:
			$GiantFeet/RightFoot/Sole.disconnect("stomp", self, "stomp_character")
		
		if $Player:
			$Player/PlayerHarm.show()
			$Player/PlayerHarm/AnimationPlayer.play("move")
			#Game.player_harm = false
			$Player.can_move = false
			$Player.can_control = false
			$Player/AnimatedSprite.hide()
		
		Audio.play_sfx("stomp_hit")
		game_stop = true
		Utils.interpolate($Camera, "automatic_camera_movement", $Camera.automatic_camera_movement, 0, 0.85)
		if Game.effects: 
			Game.effects.fade_in_black(0.4)
		Utils.execute_after(self, "game_over", 0.6)
		Game.game_speed = 0.6
		Audio.fade_out(0.4)


func _on_Clear_timeout():
	if $Camera.position.x > (actual_block * 1600 - 400):
		load_next_block()

	for platform in get_tree().get_nodes_in_group("Platform"):
		if platform.position.x < ($Camera.position.x - 6000): platform.queue_free()


func garbage_clear():
	for platform in platform_blocks:
		platform.queue_free()


func update_hiscore():
	var actual_timer = MemoryCard.get_hiscore(Game.character).split(",")
	var final_timer = ""
	
	if timer > int(actual_timer[0]):
		final_timer = str(timer)
	else:
		final_timer = actual_timer[0]
	final_timer = final_timer + ","
	if timer > int(actual_timer[1]):
		final_timer = final_timer + str(Game.coins)
	else:
		final_timer = final_timer + actual_timer[1]
	
	MemoryCard.register_hiscore(Game.character, final_timer)


func game_over():
	leaving_scene = true
	update_hiscore()
	Game.game_speed = 1
	MemoryCard.add_coins(Game.coins)
	
	garbage_clear()
	
	Game.next_level()
