extends KinematicBody2D

export var vida = 2
export var speed = 70
export var type = 1

var enemy_id = 0

var bullet = preload('res://bullet.tscn')

func damage(arg, id):
	vida += arg
	get_tree().get_nodes_in_group('server')[0]._enemy_dmg(enemy_id)
	if vida <= 0:
		get_tree().get_nodes_in_group('enemy_authority')[0].death_count(id)
		queue_free()

var motion = Vector2()
var target
onready var reaction_time = int(rand_range(20,60))

var dir_buffer = 0

var tick = 20
export var tickrate = 4
var state = 'runaround'
var fliph = false

func _physics_process(delta):
	match state:
		'runaround':
			type = 0 if motion.x == 0 else 1
			fliph = motion.x > 0 and motion.x != 0
			if target == null: _ready()
			if target == null: return
			dir_buffer += 1
			if fmod(dir_buffer,reaction_time) == 0:
				if is_instance_valid(target): motion.x = (target.global_position - global_position).normalized().x * speed
			motion.y += 15
			if motion.y > 0 and is_on_floor(): motion.y = 0
			move_and_slide(motion*tickrate,Vector2.UP)
		'shooting':
				type = 2
				tick += 1
				if fmod(tick,75) == 0:
					var instance = bullet.instance()
					instance.motion.x = 200 if fliph else -200
					instance.global_position = global_position + Vector2(0,-8)
					instance.id = name
					instance.dmg = 10
					instance.target = 'player'
					get_tree().get_nodes_in_group('proj')[0].add_child(instance)

func _on_Area2D_body_entered(body):
#	print(body)
	if body.is_in_group('players'):
		var array = get_tree().get_nodes_in_group('players')
		array.shuffle()
		if array.size() > 0:
			target = array[0]
	pass # Replace with function body.
