extends ReferenceRect

export var speed : float = 5.0
const BULLET_PATH = "res://objects/characters/monsters/03/bullet.tscn"

var velocity = Vector2(speed, 0)
export var cooldown_time: float = 3.0
export var bullet_speed: float = 3.0
export var damage: int = 10
onready var level = get_parent()

var cooldown = false
onready var bullet_scene = preload(BULLET_PATH)

var bullet_vector = Vector2.ZERO

# Called when the node enters the scene tree for the first time.
func _ready():
	randomize()
	$monster.position.x = fmod(randi(), rect_size.x)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	pass

func _physics_process(delta):
	# Move only if shoot animation is not played
	if not $monster/Animation.is_playing():
		_movement()
	
	# Check angle and distance
	var angle = $monster.global_position.angle_to_point(GlobalState.player.global_position)
	var rounded_angle = fmod(abs(round(rad2deg(angle))), 90)
	var distance = $monster.global_position.distance_to(GlobalState.player.global_position)
	var direction = ($monster.global_position - GlobalState.player.global_position).normalized()
	var player_is_left = direction.x > 0
	
	# Shoot if in right distance/angle
	if rounded_angle == 45 and cooldown == false \
	and player_is_left != $monster/AnimatedSprite.flip_h \
	and GlobalState.player.global_position.y <= rect_global_position.y + rect_size.y:
		cooldown = true
		# calculate bullet velocity
		bullet_vector = ($monster.global_position - GlobalState.player.global_position).normalized()
		$monster/CastSound.play()
		$monster/Animation.play("shoot")
		yield(get_tree().create_timer(cooldown_time), "timeout")
		cooldown = false

func _movement():
	# Move monster
	$monster.position += velocity
		
	if $monster.position.x >= rect_size.x or $monster.position.x <= 0:
		velocity.x = -velocity.x
	
	$monster/AnimatedSprite.flip_h = velocity.x > 0


func _on_Animatio_finished(anim_name):
	if anim_name == "shoot" and $monster/Animation.current_animation_position != 0:
		# generate bullet
		var bullet = bullet_scene.instance()
		bullet.global_position = $monster.global_position
		if $monster/AnimatedSprite.flip_h:
			bullet.global_position.x += 70
		bullet.velocity = bullet_vector * bullet_speed
		bullet.damage = damage
		level.add_child(bullet)
		$monster/ShootSound.play()		
		$monster/Animation.play_backwards("shoot")
		
