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

public class EnemyMoves : MonoBehaviour {

    [SerializeField]
    Transform target;

    public Transform awal;

     bool _playerinrange;

    public float timepocongsadar,time;
	public float minPoconSadar, maxPocongSadar;
    public Transform[] patroli;
    private NavMeshAgent nav;

    Animator anim;
    void Awake()
    {
        Assert.IsNotNull(target);
    }

	// Use this for initialization
	void Start () {
        nav = GetComponent<NavMeshAgent>();
        anim = GetComponent<Animator>();
        timepocongsadar = Random.Range(minPoconSadar, maxPocongSadar);
    
    }
	
	// Update is called once per frame
	void Update () {
        time += (Time.deltaTime * 2);
        if (time > timepocongsadar)
        {
            if (Vector3.Distance(transform.position, target.transform.position) < 10 && Vector3.Distance(transform.position, awal.transform.position) < 10)
            {
                if (time > timepocongsadar)
                    _playerinrange = true;

            }
            else if(Vector3.Distance(transform.position, target.transform.position) > 10 && Vector3.Distance(transform.position, awal.transform.position) > 10)
            {
                nav.SetDestination(awal.position);
               
                _playerinrange = false;
            }

            if (_playerinrange)
            {
                nav.SetDestination(target.position);
            }
            else
            {
                StartCoroutine(backtime());
            }
        }
      
    }

    IEnumerator backtime()
    {
        if (Vector3.Distance(transform.position, awal.transform.position) < 2)
        {
            timepocongsadar = Random.Range(minPoconSadar, maxPocongSadar);
            yield return null;
            time = 0;
        }
    }

 
   

}
