using UnityEngine;
using System.Collections;

public class PatrolMovement : MonoBehaviour {

    public Vector3 positionA, positionB;
    public float speed;
    public float horizontalThreshold, verticalThreshold;
    public float waitingTime = 0;

    private Vector3 _actualPosition, _targetPosition;
    private MovingScript.Dir direction = MovingScript.Dir.NONE;
    private Animator _animator;
    private float _timeWaiting = 0;

    private enum Going
    {
        AB,
        BA,
        STOP
    }

    private Going _goingTo = Going.AB;

	// Use this for initialization
	void Start () {
        _actualPosition = positionA;
        _targetPosition = positionB;
        transform.position = _actualPosition;

        _animator = GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update () {

        float l_hDir = _targetPosition.x - _actualPosition.x;
        float l_vDir = _targetPosition.y - _actualPosition.y;

        direction = MovingScript.getDirection(l_hDir, l_vDir);

        MovingScript.setAnimation(_animator, direction, transform);

        MovingScript.setMovement(_animator, transform, direction, l_hDir, l_vDir, speed);

        _actualPosition = transform.position;

        if (Mathf.Abs(l_hDir) < horizontalThreshold && Mathf.Abs(l_vDir) < verticalThreshold)
        {
            if (waitingTime != 0 && _timeWaiting < waitingTime)
            {
                _timeWaiting += Time.deltaTime;
            }
            else if (_timeWaiting >= waitingTime && _goingTo == Going.AB)
            {
                _timeWaiting = 0;
                _goingTo = Going.BA;
                _targetPosition = positionA;
            }
            else if (_timeWaiting >= waitingTime && _goingTo == Going.BA)
            {
                _timeWaiting = 0;
                _goingTo = Going.AB;
                _targetPosition = positionB;
            }
        }
	
	}
}
