extends Node2D

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var gravity_vector = ProjectSettings.get_setting("physics/2d/default_gravity_vector")
var player = load("res://scenes/pDasher.tscn")
var level = load("res://scenes/levels/level_1.tscn")
var direction: int = 1
var paused: bool = false
var asp: AudioStreamPlayer
var switch_gravity_sound = preload("res://audio/switch_gravity.wav")


## WORLD METHODS
func switch_gravity():
	gravity_vector =  gravity_vector.rotated(deg_to_rad(180))
	
func switch_direction():
	print("changing")
	direction *= -1

## NAVIGATION
func player_fail():
	get_tree().change_scene_to_file("res://scenes/UI/End.tscn")
	
func player_win():
	get_tree().change_scene_to_file("res://scenes/UI/Win.tscn")

func _ready():
	
	asp = $AudioStreamPlayer
	
	#load player and level
	get_node("/root/World").add_child( player.instantiate() ) #absolute way...
	get_node("/root/World").add_child( level.instantiate() ) #relative way meaning <ME> or whatever node this script is attached to.
	
	# manage signals connections
	var abysses = $Level/Abysses.get_children()
	for abyss in abysses:
		abyss.body_entered.connect( _on_abyss_body_entered )
		
	var gravity_switches = $Level/Switches/Gravity.get_children()
	for gswitch in gravity_switches:
		gswitch.body_entered.connect( _on_gswitch_body_entered )
	
	var direction_switches = $Level/Switches/Direction.get_children()
	for dswitch in direction_switches:
		dswitch.body_entered.connect( _on_dswitch_body_entered )
		
		
	var checkpoints = $Level/Checkpoints.get_children()
	for checkpoint in checkpoints:
		#print( checkpoint )
		checkpoint.body_entered.connect( _on_checkpoint_body_entered )

## MAIN
#func _process(delta):
	#pass

##SIGNAL HANDLING
func _on_abyss_body_entered(body):
	#check that body is player
	player_fail()
	#print( str(body) + " se fue pal hoyo" )

func _on_gswitch_body_entered(body):
	#check type of switch
	#body.get_node("AnimationPlayer").spin()
	asp.stream = switch_gravity_sound
	asp.play()
	switch_gravity()

func _on_dswitch_body_entered(body):	
	var dasher = get_node("/root/World/pDasher")
	dasher.switch_direction()
	
	

func _on_checkpoint_body_entered(body):
	body.direction = 0;
	$Timer.start()

func _on_timeout():	
	player_win()
