extends "res://scripts/enemy.gd"

var dir = Vector2()
var pos_x = 0
var offset = 0
var amplitude = 100
var period = 10
var mode = 0

var shoot_counter = 8
onready var bullet_scene = load("res://scenes/bullet_b.tscn")

func _process(delta):
	if mode == 0:
		offset = sin(range_lerp(position.y, 0, 240, 0, period)) * amplitude
	elif mode == 1:
		offset = cos(range_lerp(position.y, 0, 240, 0, period)) * amplitude
	position.y += dir.y * speed * delta
	position.x = pos_x + offset 
	if position.y > 200:
		dir.y = -1
	elif position.y < 24:
		dir.y = 1
	
func death():
	self.monitoring = false
	get_parent()._on_enemy_death(2)
	var e = get_parent().explossion_scene.instance()
	e.position = position
	get_tree().root.add_child(e)
	global.game.get_node("bg/anim").play("explossion")
	global.change_score(score_bonus)
	$explossion.play()
	queue_free()

func _on_enemy_1_area_entered(area):
	if area.name == "player":
		if area.shield == false:
			area.death()
		else:
			pass
		return
	area.queue_free()
	apply_damage()
	
func apply_damage():
	health -= 1
	if health == 0:
		death()
		return
	$anim.play("hit")
	var h = get_parent().hit_scene.instance()
	h.position = Vector2(position.x + rand_range(-32, 32), position.y)
	get_tree().root.add_child(h)
	
	
func respawn():
	death()
	
#func back():
#	set_process(false)
#	$timer.wait_time = 1
#	$timer.start()
#	yield($timer,"timeout")
#	print("back")
#	dir = Vector2(0, -1)
#	speed = 500 
#	$sprite.flip_v = true
#	set_process(true)

func shoot():
	var bullet_1 = bullet_scene.instance()
	var bullet_2 = bullet_scene.instance()
	bullet_1.global_position =  $shoot_pos_1.global_position
	bullet_2.global_position =  $shoot_pos_2.global_position
	get_parent().add_child(bullet_1)
	get_parent().add_child(bullet_2)
	$bullet_time.start()
	
func _on_bullet_time_timeout():
	shoot_counter -= 1
	if shoot_counter > 0:
		shoot()
	else:
		shoot_counter = 8
		$reloading_time.start()
	
func _ready():
	$bullet_time.connect("timeout", self, "_on_bullet_time_timeout")
	$reloading_time.connect("timeout", self, "_on_bullet_time_timeout")
	dir = Vector2(0, 1)
	shoot()
