extends Node2D

onready var global: Node = get_node("/root/Global")
onready var sprite: Sprite = $Sprite
onready var animation_player: AnimationPlayer = $AnimationPlayer

var speed: int = 8
var is_moving: bool = false
var pos_final: Vector2
var obj_action = null
var is_inactive: bool = false

func _ready() -> void:
	global.player = self
	print(global.player)

func _process(delta: float) -> void:
	if is_inactive:
		return
	if is_moving:
		var dis: float = global_position.distance_squared_to(pos_final)
		var dir: Vector2 = global_position.direction_to(pos_final)
		var spd: float = speed * delta
		if dis < spd:
			animation_player.play("Idle")
			global_position = pos_final
			action()
			is_moving = false
		else:
			animation_player.play("Walk", -1, spd * 5)
			#animation_player.playback_speed = spd * 5
			global_position += dir * spd
			
			var side: float = sign(pos_final.x - global_position.x)
			
			if side < 0:
				sprite.flip_h = true
			elif side > 0:
				sprite.flip_h = false
		
		#global_position.x += side.x * speed * delta
		#global_position.y += side.y * speed * delta

func move_to_point(pos: Vector2) -> void:
	if global_position == pos:
		action()
		return
	pos_final = pos
	animation_player.seek(0.0)
	animation_player.play("Prepare")
	
	is_inactive = true
	yield(animation_player, "animation_finished")
	is_inactive = false
	is_moving = true

func action() -> void:
	if obj_action == null:
		return
	if obj_action.sound != "":
		global.play_sound(obj_action.sound)
	if obj_action.player_facing != obj_action.PlayerFacing.NULL:
		sprite.flip_h = bool(obj_action.player_facing)
	match obj_action.type:
		"action":
			animation_player.seek(0.0)
			if obj_action.player_animation != "":
				animation_player.play(obj_action.player_animation)
			elif obj_action.next_scene != "":
				animation_player.play("Think")
			else:
				animation_player.play("Dunno")
			
			is_inactive = true
			yield(animation_player, "animation_finished")
			is_inactive = false
			print(obj_action.name)
			
			obj_action.emit_signal("used")
			if global.use_item:
				animation_player.play("Dunno")
				obj_action.emit_signal("item_used", \
					global.inventory.current_slot)
				global.use_item = false
			else:
				global.load_room_scene(obj_action.next_scene)
		"door":
			if obj_action.next_scene == "":
				return
			
			var tran: AnimationPlayer = global.transition_player
			tran.play("Show")
			is_inactive = true
			yield(tran, "animation_finished")
			is_inactive = false
			obj_action.emit_signal("used")
			#tran.play("Hide")
			#var room: Node = global.game.get_node("Room")
			global.change_room(obj_action.next_scene)
			global_position = obj_action.destination
		"move":
			pass
	
