using UnityEngine;
using System.Collections;

public class QueueScript : MonoBehaviour {

    public float minWaitingTime, maxWaitingTime;
    public int seed = 0;
    public float speed = 0;

    private float _timeWaiting = 0;
    private bool _waiting = false;
    private bool _moving = true;
    private float _timeToWait = 0;
    private Animator _animator;
    private BasicScript _basicScript;

	// Use this for initialization
	void Start () {
        _animator = GetComponent<Animator>();
        _basicScript = GetComponent<BasicScript>();
	}
	
	// Update is called once per frame
	void Update () {

        if (_waiting)
        {
            _timeWaiting += Time.deltaTime;

            if (_timeWaiting >= _timeToWait)
            {
                _timeWaiting = 0;
                _waiting = false;
                _moving = true;
            }
        }

        if (_moving)
        {
            MovingScript.setAnimation(_animator, MovingScript.Dir.EAST, transform);
            MovingScript.setMovement(_animator, transform, MovingScript.Dir.EAST, 1f, 0f, speed);
        }
        else
        {
            MovingScript.setAnimation(_animator, MovingScript.Dir.NONE, transform);
        }
	
	}

    void OnTriggerEnter2D(Collider2D coll)
    {
        Vector3 l_collPosition = coll.gameObject.transform.position;

        if ((l_collPosition.x < transform.position.x) || (coll.gameObject.tag == "Militar") || (coll.gameObject.tag == "SideTrigger"))
        {
            return;
        }

        Random.seed = seed;
        _timeWaiting = 0;
        _timeToWait = Random.value * (maxWaitingTime - minWaitingTime) + minWaitingTime;
        _waiting = false;
        _moving = false;

    }

    void OnTriggerStay2D(Collider2D coll)
    {
        if (!_waiting && coll.gameObject.tag == "Door")
        {
            Random.seed = seed;
            _timeWaiting = 0;
            _timeToWait = Random.value * (maxWaitingTime - minWaitingTime) + minWaitingTime;
            _waiting = true;
        }
        
    }

    void OnTriggerExit2D(Collider2D coll)
    {
        Vector3 l_collPosition = coll.gameObject.transform.position;

        if ((l_collPosition.x < transform.position.x) || (coll.gameObject.tag == "Militar") || (coll.gameObject.tag == "SideTrigger"))
        {
            return;
        }

        if (!_waiting)
        {
            Random.seed = seed;
            _timeWaiting = 0;
            _timeToWait = Random.value * (maxWaitingTime - minWaitingTime) + minWaitingTime;
            _waiting = true;
            _moving = false;
        }
    }
}
