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

public class KidController : MonoBehaviour {

    public Transform destination;

    public float StunTimeBeforeDeath = 10f;

    [HideInInspector]
    public KidState state;

    public Animator anim;
    private NavMeshAgent agent;
    private float EatTimer;
    private float TimeOfStun;

    public enum KidState
    {
        Zombie,
        Stunned,
        Eating
    }
	// Use this for initialization
	void Start () {
        agent = GetComponent<NavMeshAgent>();
        agent.destination = destination.position;

        state = KidState.Zombie;
    }
	
    public void Stun()
    {
        TimeOfStun = Time.time;
        foreach (SkinnedMeshRenderer skin in gameObject.GetComponentsInChildren<SkinnedMeshRenderer>() ) {
            skin.SetBlendShapeWeight(0, 100f);
        }
        state = KidState.Stunned;
        agent = GetComponent<NavMeshAgent>();
        agent.isStopped = true;
        anim.SetTrigger("Stun");
        agent.enabled = false;
        gameObject.layer = LayerMask.NameToLayer("StunnedKid");
    }

    void LateUpdate() {
        if ( state == KidState.Stunned ) {
            foreach (SkinnedMeshRenderer skin in gameObject.GetComponentsInChildren<SkinnedMeshRenderer>() ) {
                skin.SetBlendShapeWeight(0, 100f);
            }
            return;
        }
    }

	// Update is called once per frame
	void Update () {
        if(state == KidState.Eating)
        {
            EatTimer += Time.deltaTime;
            if(EatTimer >= 5)
            {
                Destroy(gameObject);
            }
            return;
        }
        if(state == KidState.Stunned)
        {
            if(Time.time - TimeOfStun >= StunTimeBeforeDeath)
            {
                Destroy(this.gameObject);
            }
        }

        anim.SetFloat("Speed", agent.velocity.magnitude);

        if(Vector3.Distance(transform.position, agent.destination) < 3)
        {
            agent.isStopped = true;
            anim.SetTrigger("Eat");
            state = KidState.Eating;
            EatTimer = 0.0f;
        }
	}
}
