extends KinematicBody2D

var player
var motion = Vector2()
export var speed = 150
export var attackrange = 64
export var reactiontime = 1
var active = false
export var detectionzone = 128
export var exppt = 15
onready var initspeed = Vector2(sin(rand_range(0,TAU)),cos(rand_range(0,TAU)))

var dict = {
	'ovomonstro' : 20,
	'besourodourado' : 10,
	'escorpiao' : 10,
}

func _ready():
	player = get_tree().get_nodes_in_group('player')[0]
	var array = []
	for x in $types.get_animation_list():
		if dict.has(x):
#			print(x)
			if dict[x] < player.lv: 
				array.append(x)
		else:
			array.append(x)
	array.shuffle()
	while array[0] == 'RESET':
		array.shuffle()
#	print(array)
	$types.play(array[0])
	name = array[0]
	yield(Timergen.createtime(self,0.1),'timeout')
	$Health.health = $Health.health_max
	$types.queue_free()
	yield(Timergen.createtime(self,5.0),'timeout')
	if not $VisibilityNotifier2D.is_visible_in_tree(): queue_free()
	pass # Replace with function body.

var delete_buff = 600

func _physics_process(delta):
	if player:
		for x in range(-1,1):
			for y in range(-1,1):
				if checkapproxpos(Vector2(x,y)):
					active = true
		if active:
			reactiontime -= 1
			if reactiontime == 0:
				motion = (player.global_position - global_position).normalized()
				reactiontime = 180
				$hitbox.position = motion * attackrange
			move_and_slide(motion * speed)
			$Sprite.rotation = atan2(motion.y * speed,motion.x * speed)
		else:
			move_and_slide(initspeed * speed)
			$Sprite.rotation = atan2(initspeed.y * speed,initspeed.x * speed)
#		delete_buff -= 1
#		if delete_buff < 0: 
#			if not $VisibilityNotifier2D.is_visible_in_tree():
#				queue_free()
#			delete_buff = 600

func checkapproxpos(var offset = Vector2()):
	var pos1 = Vector2(int(player.global_position.x/detectionzone), int(player.global_position.y/detectionzone))
	var pos2 = Vector2(int(global_position.x/detectionzone), int(global_position.y/detectionzone))
	if pos1.y+offset.y == pos2.y+offset.y and  pos1.x+offset.x == pos2.x+offset.x: 
		return true


func _on_VisibilityNotifier2D_screen_exited():
#	if not active: queue_free()
	pass # Replace with function body.
