extends Node2D


export var screen_size := Vector2(480, 270) 

var _grid_active_cell_origin := Vector2.ZERO

var latest_checkpoint:CheckPoint = null


func _physics_process(delta: float) -> void:
	_update_camera(delta)

func _ready() -> void:
	AudioManager.play_music(AudioManager.Music.Abandon)
	for coin in  $Coins.get_children():
		coin.connect("collected", self, "_on_coin_collected")
	for checkpoint in  $Checkpoints.get_children():
		checkpoint.connect("activated", self, "_on_checkpoint_activated")

func _on_coin_collected(amount:int):
	$HUD.on_coin_collected(amount)
	
func _on_checkpoint_activated(cp:CheckPoint):
	if latest_checkpoint != null and latest_checkpoint != cp:
		latest_checkpoint.deactivate()
	latest_checkpoint = cp
	$Player.respawn_position = cp.global_position

func _update_camera(delta:float) -> void:
	var player_position = $Player.position
	var camera_position = $Camera2D.position
	var desired_camera_position = Vector2(
		floor(player_position.x / screen_size.x) * screen_size.x,
		floor(player_position.y / screen_size.y) * screen_size.y)
	if camera_position != desired_camera_position:
		_grid_active_cell_origin = desired_camera_position
		$Camera2D.update_grid_position(desired_camera_position)

func _on_Player_landed(position:Vector2) -> void:
	pass


func _on_Player_jumping(position:Vector2) -> void:
	pass
