extends KinematicBody2D

export(String, "flock a", "flock b", "flock c") var flock
export(bool) var flying = false

const GRAVITY = 1000.0
const WALK_SPEED = 800.0
const MAIN_FLY_SPEED = 20
const FLOOR_NORMAL = Vector2(0,-1)

var velocity = Vector2()
var fly_target = Vector2()
var is_grounded = false
var siding_left = false
var anim=""
var state = null
var dir = 1
var type = "mob"

onready var states = [{name = "walk", chance = 0.4, duration = 0, multiplier = 0.1},
					 {name = "idle", chance = 0.4, duration = 0, multiplier = 0.2}, 
					 {name = "peck", chance = 0.4, duration = 0, multiplier = 0.04},
					 {name = "look", chance = 0.4, duration = 0, multiplier = 0.3},
					 {name = "soaring", chance = 0.4, duration = 0, multiplier = 0.1},    
					 {name = "fly", chance = 0.04, duration = 0, multiplier = 0.2},
					 {name = "land_on", chance = 0.4, duration = 0, multiplier = 0.1},    
					 {name = "land_off", chance = 0.4, duration = 0, multiplier = 0.1}]

onready var timer = get_node("timer")
onready var ray = get_node("sprite/ray")
onready var ray2 = get_node("sprite/ray2")

func _physics_process(delta):
	var new_anim=anim
	var new_siding_left = siding_left
	
	var state_name = state.name
	
	if state_name == "walk":
		velocity.x = WALK_SPEED * dir * delta
	elif state_name == "idle" or state_name == "peck" or state_name == "look":
		velocity.x = 0
	elif state_name == "fly":
		velocity.x = 2000 * dir * delta
		velocity.y = -4000 * delta
		
	move_and_slide(velocity, FLOOR_NORMAL)
		
	new_siding_left = (dir == -1)
	new_anim = state_name
		
	if (new_siding_left!=siding_left):
		if (new_siding_left):
			get_node("sprite").set_scale( Vector2(-1,1) )
		else:
			get_node("sprite").set_scale( Vector2(1,1) )
		siding_left=new_siding_left
	
	if (new_anim!=anim):
		anim=new_anim
		get_node("anim").play(anim)
	
func nix(): 
	state = states[7]
	
func _on_timer_timeout():
	if state.name != "fly":
		change_state()
	
func change_state():
	var i = randi() % 2
	if i == 1:
		i = randi() % 3 + 1
	state = states[i]
	state.duration = (randi() % 20 +1) * state.multiplier
	dir  = sign(rand_range(-1, 1))
	timer.set_wait_time(state.duration)
	timer.start()
	
func select_fly_target():
	pass
	
func die():
	queue_free()
	
func apply_damage(S):
	state = states[5]
	
func _ready():
	state = states[1]
	state.duration = ((randi() % 19) + 1)* state.multiplier 
	timer.set_wait_time(state.duration)
	timer.start()

func _on_area_area_entered(area):
	dir = sign(global_position.x - area.global_position.x)
	state = states[5]
