extends Camera2D

var horizontal_facing = 0
var vertical_facing = 0
var camera_horizontal_shift = 70
var camera_vertical_shift = 90

onready var prev_camera_pos = get_camera_position()
onready var tween = $ShiftTween
onready var original_x_zoom = zoom.x
onready var original_y_zoom = zoom.y

# Gets the camera limits from the tilemap of the level
# Requires "TileMap" to be a sibling of blobby
func _ready():
	_set_boundaries()

func _process(_delta: float) -> void:
	_adapt_to_movement()
	prev_camera_pos = get_camera_position()

func _set_boundaries():
	# This is ok, because it only happens on initialization
	# But it is also quite fickle
	var tilemap = get_node("../../TileMap")
	# TODO This goes wrong when overwriting old tiles with new sprites
	# New pngs -> completely new tiles and rebuild map
	var rect = tilemap.get_used_rect()
	var cell_size = tilemap.cell_size
	limit_right = rect.end.x * cell_size.x
	limit_left = rect.position.x * cell_size.x
	limit_top = rect.position.y * cell_size.y
	limit_bottom = rect.end.y * cell_size.y
	var screen_size = get_viewport_rect()
	var h_pixels = limit_right - limit_left
	var v_pixels = limit_bottom - limit_top
	#TODO Fix that it can zoom both?
	if screen_size.end.x * original_x_zoom - h_pixels > 0:
		zoom.x = h_pixels / screen_size.end.x
		zoom.y = zoom.x
	if screen_size.end.y * original_y_zoom - v_pixels > 0:
		zoom.y = v_pixels / screen_size.end.y
		zoom.x = zoom.y

# TODO Smoothing the camera limits in godot ruins this still?
func _adapt_to_movement():
	# TODO Adapt this to movement speed
	var target_offset: Vector2 = Vector2(0,0)
	var tween_v = false
	var tween_h = false
	var new_h_facing = sign(get_camera_position().x - prev_camera_pos.x)
	if new_h_facing != 0 && horizontal_facing != new_h_facing:
		horizontal_facing = new_h_facing
		target_offset.x = camera_horizontal_shift * horizontal_facing
		tween_h = true
	
	# var new_v_facing = sign(get_camera_position().y - prev_camera_pos.y)
	# if new_v_facing != 0 && vertical_facing != new_v_facing:
	# 	vertical_facing = new_v_facing
	# 	target_offset.y = camera_vertical_shift * vertical_facing
	# 	print(target_offset)
	# 	tween_v = true

	if (tween_h || tween_v):	
		#TODO Motion may be too complex
		tween.interpolate_property(
			self,
			"transform:origin",
			self.transform.origin,
			target_offset,
			1.2,
			Tween.TRANS_SINE,
			Tween.EASE_OUT
		)
		tween.start()