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

public class Gremlin : Monster
{

    const float ATTACK_RANGE = 15f;

    const float IDEAL_RANGE = 10f;

    public float moveSpeed = 2f;

    public float turnSpeed = 120;

    public float attackInterval;

    float attackDelay;

    public GameObject bullet;

    public Transform muzzle;

    // 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)
            {
                GameObject.Instantiate(bullet, muzzle.transform.position, transform.rotation);
                
                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);
        }
    }
}
