using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySlime : Enemy
{
    public float JumpInterval = 1.0f;
    public float JumpVelocity = 1.0f;
    public int Damage = 10;
    public int AttackCooldown = 10;
    public Vector2 AttackAreaExtend;

    private new Rigidbody2D rigidbody;
    private Vector2 jumpVelocity;
    private Vector2 direction;
    private int currentAttackCooldown = 0;

    public override void Start()
    {
        base.Start();
        this.rigidbody = this.GetComponent<Rigidbody2D>();
        this.direction = this.transform.right;
        StartCoroutine(jumpCoroutine());
    }

    private void TryAttack(Collider2D collision)
    {
        if (Util.IsInLayerMask(collision.gameObject.layer, TargetLayermask))
        {
            currentAttackCooldown = AttackCooldown;
            Entity e = collision.gameObject.GetComponent<Entity>();
            if (e != null && e is Player)
            {
                e.Harm(this.Damage, this, this.transform.position);
            }
        }
    }

    public void Update()
    {
        Vector3 scale = this.transform.localScale;
        scale.x = Mathf.Sign(this.direction.x);
        this.transform.localScale = scale;
        if (this.Target != null)
        {
            direction = this.Target.transform.position - this.transform.position;
        }
    }

    public void FixedUpdate()
    {
        currentAttackCooldown = Mathf.Clamp(currentAttackCooldown - 1, 0, int.MaxValue);
        Collider2D[] colliders = Physics2D.OverlapAreaAll((Vector2)this.transform.position - AttackAreaExtend, (Vector2)this.transform.position + AttackAreaExtend);
        if (currentAttackCooldown <= 0)
        {
            foreach(Collider2D collider in colliders)
            {
                TryAttack(collider); 
            }
        }
    }

    private IEnumerator jumpCoroutine()
    {
        while (true)
        {
            yield return new WaitForSeconds(this.JumpInterval);
            if (this.Target != null)
            {
                jump((direction + Vector2.up).normalized * JumpVelocity);
            }
        }
    }

    private void jump(Vector2 direction)
    {
        if (this.OnGround)
        {
            this.Animator.SetTrigger("Jump");
            this.jumpVelocity = direction;
        }
    }

    public void OnJumpAnimationEvent()
    {
        rigidbody.velocity += jumpVelocity;
    }

}
