using UnityEngine;

public class TigerController : MonoBehaviour {

    public float moveSpeed;
    public float walkSpeed;
    public float shotHeardSpeed;
    public AudioClip[] footsteps;
    public float footstepDelay;
    //public bool playerInRange;
    public float stopStalkDelay = 5f;
    public float rotationSpeed = 2f;

    protected bool playerHeard;
    protected float stopStalkTimer;
    protected AudioSource footstepSource;
    protected float footstepTimer;
    protected bool walking = false;
    protected GameObject player;
    protected Animator myAnimator;

    protected void Start () {
        footstepSource = GetComponent<AudioSource>();
        player = GameObject.FindGameObjectWithTag("Player");
        myAnimator = GetComponent<Animator>();
    }
	
	protected void Update () {
        if (playerHeard) {
            MoveTowardsPlayer();
        }
	}

    protected void CreateFootstepSound() {
        if (Time.time > footstepTimer) {
            footstepTimer = Time.time + footstepDelay;
            footstepSource.PlayOneShot(footsteps[Random.Range(0, footsteps.Length)]);
        }
    }

    public void HeardPlayer() {
        playerHeard = true;
        //Debug.Log("Growl...");
        stopStalkTimer = Time.time + stopStalkDelay;
        myAnimator.SetTrigger("Move");
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Death") {
            Destroy(transform.root.gameObject);
        }
    }

    protected void MoveTowardsPlayer()
    {
        if (Time.time < stopStalkTimer)
        {
            transform.LookAt(player.transform.position);
            Vector3 tempRot = transform.rotation.eulerAngles;
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, tempRot.y, 0), rotationSpeed * Time.deltaTime);

            transform.position += transform.forward * walkSpeed * Time.deltaTime;

            CreateFootstepSound();
            
        }
        else if(playerHeard){
            playerHeard = false;
            myAnimator.SetTrigger("Stop");
            moveSpeed = walkSpeed;
        }
    }
}
