class_name CameraGuide
extends KinematicBody2D

export var debug_camera_guide :bool = false

var game_size :Vector2
onready var window_scale :float
onready var viewport = $"%Viewport"
## Camera guide doesn't really need to care if there's a camera
#onready var camera_2d = $"%Camera2D"

var _is_tracking :bool = true

# Called when the node enters the scene tree for the first time.
func _ready():
	game_size = viewport.size
	window_scale = (OS.window_size / game_size).x
	assert(game_size != Vector2(0,0), str(get_path()) + " : No game_size set.")
	## Camera guide doesn't really need to care if there's a camera
	#assert(camera_2d != null, str(get_path()) + " : No Camera Node Found.")

	if debug_camera_guide:
		print(get_path(), "\n",
		"\tSize:", game_size,
		"\tScale:", window_scale)
	## Do not track until told to
	disable_tracking()


func enable_tracking() -> void:
	##TODO: add extra collission checks here to make sure we aren't stuck maybe?
	_is_tracking = true
	self.set_physics_process(true)

func disable_tracking() -> void:
	_is_tracking = false
	self.set_physics_process(false)

func reset_position() -> void:
	## Set to half screen
	global_position = game_size / 2

var flip_tracker = 0.0
var stuck_check: bool
func _physics_process(_delta):
	var pos = global_position
	#pos = pos.move_toward(PlayerInfo.player_position, delta)
	#pos = lerp(pos, PlayerInfo.player_position, delta )
	var dir_to = Vector2(0,0)

	if (PlayerInfo.get_player_data(0)):
		var player_position = PlayerInfo.get_player_data(0).player_position

		# Calculate how far the player is from object
		var diff_to = (player_position - pos)
		var dist_to = (player_position - pos).length()
		
		# Determine the chase direction of player is past the threshold
		# Try to prevent bounce
		if (is_on_wall() or is_on_floor() or is_on_ceiling()) and abs(diff_to.x) > 10:
			dir_to = pos.direction_to(player_position)
		elif !(is_on_wall() or is_on_floor() or is_on_ceiling()) and abs(diff_to.y) > 10:
			dir_to = pos.direction_to(player_position)

		if debug_camera_guide:
			UiManager.debug_text = ( "-Camera Guide-" + 
				# str(PlayerInfo.player_position.snapped(Vector2(0.01,0.01))) + 
				"\n" + str(is_on_ceiling()) + str(is_on_floor()) + str(is_on_wall()) +
				"\nPP: {0}, {1}".format({"0":"%7.2f" % PlayerInfo.player_position.x, "1":"%7.2f" % PlayerInfo.player_position.y}) +  
				#"\nKB: " + str(global_position.snapped(Vector2(0.01,0.01))) + 
				"\nKB: {0}, {1}".format({"0":"%7.2f" % global_position.x, "1":"%7.2f" % global_position.y}) +  
				"\nDir to: {0}, {1}".format({"0":"%7.2f" % dir_to.x, "1":"%7.2f" % dir_to.y}) +  
				"\nPoint to: {0}, {1}".format({"0":"%7.2f" % diff_to.x, "1":"%7.2f" % diff_to.y})  
				#"\nDT: %7.2f" % dist_to 
			) 
		move_and_slide(dir_to * 180.0 )
		
	#	flip_tracker += delta
	#	if flip_tracker < 10:
	#		move_and_slide(Vector2(60.2,0))
	#	elif flip_tracker < 20:
	#		move_and_slide(Vector2(-60.2,0))
	#	else:
	#		flip_tracker = 0.0
