extends Area2D

onready var bullet_scene = load("res://scenes/enemie_bullet.tscn")

var destroyed = false 

var damage = 12
var health = 10

var y_speed = 2
var x_speed = 4

var y = 0
var new_y = 0

var x = 0
var new_x = 0
var dir_x = 1

func _process(delta):
	new_y += y_speed * delta
	if ceil(y) != ceil(new_y):
		y = new_y
		position.y += 1
		
	new_x += x_speed * delta
	if ceil(x) != ceil(new_x):
		x = new_x
		position.x += 1 * dir_x
		
	if position.x < 0 or position.x > 32:
		dir_x *= -1
		position.x += 1 * dir_x
		
func shoot():
	var bullet = bullet_scene.instance()
	bullet.global_position = $bullet_pos.global_position
	get_parent().add_child(bullet)
	$bullet_time.start()
	$shot.play()
	
func _on_area_entered(area):
	if destroyed:
		return
	var t = area.type
	if t == "bullet":
		area.queue_free()
		if apply_damage(area.damage):
			destroyed = true
			destroy()
	elif t == "rocket":
		area.queue_free()
		var _exp = load("res://scenes/explossion.tscn").instance()
		_exp.global_position = global_position
		get_parent().add_child(_exp)
		get_parent().flash()
		if apply_damage(area.damage):
			destroyed = true
			yield(get_tree().create_timer(0.15), "timeout")
			destroy()
	elif t == "body":
		if !area.apply_damage(damage):
			destroyed = true
			destroy()
			get_parent().damage()
		else:
			area.destroy()
			get_parent().flash()
			yield(get_tree().create_timer(0.15), "timeout")
			destroyed = true
			destroy()
		
func apply_damage(d):
	health -= d
	if health <= 0:
		return true
	else:
		$anim.play("damage")
		$hit.play()
		return false
		
func destroy():
	$life_time.disconnect("timeout", self, "queue_free")
	var _exp = load("res://scenes/explossion.tscn").instance()
	_exp.global_position = Vector2(global_position.x - 2, global_position.y)
	get_parent().add_child(_exp)
	get_parent().flash()
	yield(get_tree().create_timer(0.15), "timeout")
	_exp = load("res://scenes/explossion.tscn").instance()
	_exp.global_position = Vector2(global_position.x + 2, global_position.y)
	get_parent().add_child(_exp)
	get_parent().n -= 1
	queue_free()
#
func _ready():
	$life_time.connect("timeout", self, "queue_free")
	$life_time.start()
	self.connect("area_entered", self, "_on_area_entered")
	$bullet_time.connect("timeout", self, "shoot")
	$bullet_time.start()
	yield($ready_time, "timeout")
	monitoring = true
