extends Node2D


onready var tile_map = $"../Environment/Ground"
onready var sprite = $"Sprite"
onready var annie = $"AnimationPlayer"
onready var ray = $"RayCast2D"
onready var interactor = $"Interactor"

var isMoving = false
var velocity = 120

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _physics_process(delta):
	if not isMoving:
		return
		
	if global_position == sprite.global_position:
		# go from animated to idle
		
		if not (Input.is_action_pressed("ui_up") or Input.is_action_pressed("ui_down") or Input.is_action_pressed("ui_left") or Input.is_action_pressed("ui_down") or Input.is_action_pressed("ui_right")):
			annie.play("Idle" + annie.current_animation.substr(3))
		
		isMoving = false
		return
	
	sprite.global_position = sprite.global_position.move_toward(global_position, delta * velocity)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):	
	if isMoving:
		return
		
	if Input.is_action_just_pressed("ui_accept") and interactor.is_colliding():
		print(interactor.get_collider().name)
	
	if Input.is_action_pressed("ui_up"):
		annie.play("Run_Up")
		move(Vector2.UP)
	elif Input.is_action_pressed("ui_down"):
		annie.play("Run_Down")
		move(Vector2.DOWN)
	elif Input.is_action_pressed("ui_left"):
		annie.play("Run_Left")
		move(Vector2.LEFT)
	elif Input.is_action_pressed("ui_right"):
		annie.play("Run_Right")
		move(Vector2.RIGHT)
	pass
	
func move(direction: Vector2):
	
	
	# get current and target tile coordinate vectors
	var current_tile = tile_map.world_to_map(global_position)
	var target_tile = current_tile + direction
	
	# set moving flag to lock out input
	isMoving = true
	
	ray.cast_to = direction*16
	interactor.cast_to = direction*16
	
	ray.force_raycast_update()
	
	if(ray.is_colliding()):
		return
	
	# move the node to target position
	global_position = tile_map.map_to_world(target_tile)
	
	# move back character sprite for animation/delay
	sprite.global_position = tile_map.map_to_world(current_tile)
	
	pass 
