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

public class Caster : Monster {

    const float ATTACK_RANGE = 20f;

    const float IDEAL_RANGE = 14f;

    const float IDEAL_RANGE_MIN = 12f;

    public float moveSpeed = 1.2f;

    public float turnSpeed = 90;

    public float attackInterval;

    float attackDelay;

    public GameObject bullet;

    public Transform muzzle;

    Animator anim;

    void Awake()
    {
        anim = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!GlobalUpdate())
            return;

        transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(playerReference.transform.position - transform.position, Vector3.up), turnSpeed * Time.deltaTime);

        attackDelay = Mathf.Max(0, attackDelay - Time.deltaTime);

        if (attackDelay == 0)
        {
            Vector3 distance = playerReference.transform.position - transform.position;
            if (distance.sqrMagnitude <= ATTACK_RANGE * ATTACK_RANGE && Mathf.Abs(Vector3.Angle(transform.forward, distance)) <= 25f)
            {
                anim.SetTrigger("attacking");
                for (int i = 0; i < 7; i++)
                {
                    GameObject bulletGo = GameObject.Instantiate(bullet, muzzle.transform.position, Quaternion.Euler(0, Random.Range(-20, 20), 0) * transform.rotation);
                    bulletGo.GetComponent<Projectile>().velocity += Random.Range(0, 5);
                }
                attackDelay += attackInterval;
            }
        }
    }

    void FixedUpdate()
    {
        if (!GlobalFixedUpdate())
            return;

        Vector3 distance = playerReference.transform.position - transform.position;

        if (distance.sqrMagnitude > IDEAL_RANGE * IDEAL_RANGE)
        {
            character.SimpleMove(distance.normalized * moveSpeed);
        }
        else if (distance.sqrMagnitude < IDEAL_RANGE_MIN * IDEAL_RANGE_MIN)
        {
            character.SimpleMove(distance.normalized * -moveSpeed);
        }
    }
}
