extends KinematicBody2D

export (NodePath) var city
export (NodePath) var market
export (NodePath) var company
export (NodePath) var moneyframe
export (Vector2) var spawn


var speed_spawn = 400
var speed_phys = 5
var speed_phys_max = 550
var dest  = 0

var current_target = null

var wait_start = 0.5
var wait_market = 1.8
var wait_city = 1.8
var wait_final = 0.2

var velocity = Vector2()

var oldNodePosHitAngle = null

func _ready():
	get_node("sprite").texture = load("res://sprites/bringmans/bm"+str(randi()%10).pad_zeros(2)+".png")


func state_next():
	velocity = Vector2.ZERO
	oldNodePosHitAngle = null
	current_target = null
	dest+=1


func _process(delta):
	if dest == 0:
		move_to_pos(spawn, delta)
	elif dest == 1:
		wait_start-=delta
		if wait_start <= 0: state_next()
	elif dest == 2:
		move_to_node(market, delta)
	elif dest == 3:
		wait_market-=delta
		if wait_market <= 0: state_next()
	elif dest == 4:
		move_to_node(city, delta)
	elif dest == 5:
		wait_city-=delta
		if wait_city <= 0: state_next()
	elif dest == 6:
		move_to_node_pos(company, delta)
	elif dest == 7:
		wait_final-=delta
		if wait_final <= 0: state_next()
	elif dest == 8:
		get_node(moneyframe).incMoney()
		queue_free()


func move_to_node(np, delta):
	var node = get_node(np)
	velocity += (node.position - position).normalized() * speed_phys
	
	current_target = node


func move_to_node_pos(np, delta):
	var node = get_node(np)
	velocity += (node.position - position).normalized() * speed_phys
	
	var angleNow = sign((node.position - position).angle())
		
	if oldNodePosHitAngle == null:
		oldNodePosHitAngle = angleNow
	else:
		if angleNow != oldNodePosHitAngle:
			state_next()
		else:
			oldNodePosHitAngle = angleNow


func move_to_pos(pos, delta):
	velocity = Vector2.ZERO
	current_target = null
	
	var angle_prev = sign((pos - position).angle())
	
	position = position.move_toward(pos, delta * speed_spawn)
	
	var angle_post = sign((pos - position).angle())
	
	if angle_prev != angle_post:
		state_next()


func radius():
	return get_node("sprite").texture.get_width()*get_node("sprite").transform.get_scale().x/2


func _physics_process(delta):
	if (velocity.length_squared() == 0): return
	
	velocity = move_and_slide(velocity, Vector2(0, -1))
	
	if velocity.length() > speed_phys_max:
		velocity = velocity.normalized() * speed_phys_max
	
	if current_target != null:
		var slide_count = get_slide_count()
		if slide_count:
			var collision = get_slide_collision(slide_count - 1)
			var collider = collision.collider
			if collider == current_target:
				state_next()
