class_name Player
extends Area2D

signal hit

enum State {SLEEPING, DODGING, DEAD}

export var speed = 400 # pixel / sec
var screen
var target = Vector2()
var target_reached = true
var _current_state


func spawn(pos):
	_current_state = State.DODGING
	$CollisionShape2D.disabled = false
	go_to(pos)


func sleep():
	_current_state = State.SLEEPING
	$AnimatedSprite.animation = "sleep"
	$AnimatedSprite.play()


func die():
	_current_state = State.DEAD
	$AnimatedSprite.animation = "die"
	$AnimatedSprite.play()

func _ready():
	screen = get_viewport_rect()
	sleep()


func _process(delta: float):
	if _current_state == State.DODGING:
		dodge(delta)


func dodge(delta: float):
	var velocity = get_velocity_from_action()
	if velocity == Vector2.ZERO :
		velocity = get_velocity_from_target(delta)
	
	if velocity.length_squared() > 0:
		velocity = velocity.normalized() * speed
		position += velocity * delta
		position.x = clamp(position.x, 0, screen.size.x)
		position.y = clamp(position.y, 0, screen.size.y)
		$AnimatedSprite.animation = "move"
		$AnimatedSprite.flip_h = velocity.x < 0
	else:
		$AnimatedSprite.animation = "idle"


func go_to(pos: Vector2):
	target = pos
	target_reached = false


func _input(event):
	if event is InputEventMouseButton or event is InputEventMouseMotion :
		go_to(event.position)


func _on_Player_body_entered(_body):
	die()
	emit_signal("hit")
	$CollisionShape2D.set_deferred("disabled", true)

func get_velocity_from_action() -> Vector2:
	var velocity = Vector2()

	if Input.is_action_pressed("ui_right"):
		velocity.x += 1
	if Input.is_action_pressed("ui_left"):
		velocity.x -= 1
	if Input.is_action_pressed("ui_down"):
		velocity.y += 1
	if Input.is_action_pressed("ui_up"):
		velocity.y -= 1

	return velocity;


func get_velocity_from_target(delta):
	if target_reached :
		return Vector2.ZERO

	var path = target - position

	if path.length_squared() < speed * speed * delta * delta :
		target_reached = true
		return Vector2.ZERO

	return path
