using UnityEngine;
using System.Collections;

public class MoveAlongPath : MonoBehaviour
{
    public GameObject[] wayPoints;
    public float[] stopTimes;
    public float duration;

    private Transform lastPosition;
    private Transform nextPosition;
    private int targetID;
    private bool forward;
    private float elapsedTime;

    public Vector3 Velocity;
    //{
    //    get;
    //    private set;
    //}

    private Vector3 _previousPosition;

    void Start()
    {
        _previousPosition = transform.position;
        targetID = 1;
        lastPosition = wayPoints[0].transform;
        nextPosition = wayPoints[1].transform;
        forward = true;
        elapsedTime = 0;

        StartCoroutine(Animate());
    }

    IEnumerator Animate()
    {
        while (true)
        {
            int currentTarget = targetID;
            float t = elapsedTime / duration;
            transform.position = Vector3.Slerp(lastPosition.position, nextPosition.position, t);
            Velocity = (transform.position - _previousPosition) / Time.deltaTime;
            _previousPosition = transform.position;
            elapsedTime += Time.deltaTime;
            if (t >= 1)
            {
                if (forward)
                {
                    targetID++;
                    if (targetID == wayPoints.Length)
                    {
                        targetID -= 2;
                        forward = false;
                    }
                }
                else
                {
                    targetID--;
                    if (targetID < 0)
                    {
                        targetID = 1;
                        forward = true;
                    }
                }

                yield return new WaitForSeconds(stopTimes[currentTarget]);
                elapsedTime = 0;
                lastPosition = nextPosition;
                nextPosition = wayPoints[targetID].transform;
            }

            yield return null;
        }
    }
}
