extends Area2D

var COLL = preload("res://src/Collision_Bits.gd")
var Player = preload("res://src/Player.gd")
var Fireball = preload("res://src/Fireball.gd")
var Ice = preload("res://src/Ice.gd")
var Spark = preload("res://src/Spark.gd")

var tex = preload("res://images/zombie.png")
var spr
var dir = Vector2()
var speed = 40
var minSpeed = 10
var maxSpeed = 60
var aSign = 1.0
var aSpeed = 30.0
var side
var world

var audio

func _init(side):
  spr = Sprite.new()
  spr.set_texture(tex)
  add_child(spr)
  spr.offset = Vector2(0, -0.5 * tex.get_height())
  # COLLISION
  var my_shape = RectangleShape2D.new()
  my_shape.set_extents(spr.scale * Vector2(spr.texture.get_size().x / 2, spr.texture.get_size().y / 4))
  var collision = CollisionShape2D.new()
  collision.set_shape(my_shape)
  collision.set_position(spr.scale * spr.offset * Vector2(1.0, 0.5))
  add_child(collision)
  set_collision_layer_bit(COLL.PLAYER, false)
  set_collision_layer_bit(COLL.POWERUP, true)
  connect("area_entered", self, "_hitCallback")
  # LOCATION
  self.dir = -1 * side
  if self.dir.x == -1:
    spr.set_flip_h(true)
  self.side = side
  add_to_group("enemies")

func _ready():
  world = $"/root/World"
  position = world.centerPos + 1.25 * side * world.centerPos + Vector2(0.0, -10.0) + Vector2(randf()*10-5, randf()*10-5)
  
func _process(delta):
  if speed > maxSpeed:
    aSign = -1.0
  elif speed < minSpeed:
    aSign = 1.0
  speed += aSign * aSpeed * delta
  position.x += speed * dir.x * delta
  position.y += speed * dir.y * delta
  if position.x < -(spr.texture.get_size().x + 500) or \
       position.x > world.worldSize.x + spr.texture.get_size().x + 500:
    queue_free()
  
func _hitCallback(target):
  if target is Fireball or target is Spark:
    queue_free()
  if target is Fireball or target is Ice:
    target.queue_free()
  if target is Ice:
    speed *= 0.7
    minSpeed *= 0.7
    maxSpeed *= 0.7
    spr.modulate = Color(0.6, 0.8, 1)
  elif target is Player:
    $"/root/World".gameOver()
    speed = 0
    aSpeed = 0