using UnityEngine;
using System.Collections;

public class MoverController : EnemyController {

    public Transform[] moveRoute;
    public float moveSpeed;
    public float moveCoolDown = 2;

    public int routeLoc = 0;
    private int routeMax;
        
    private bool isMove = false;
    private float lastMoveTime = 0.5f;

    // Use this for initialization
    protected override void Start () {
        base.Start();
	    routeMax = moveRoute.Length;
        transform.position = moveRoute[routeLoc % routeMax].position;
    }
	
	// Update is called once per frame
	void FixedUpdate () {

        if (Time.time - lastShotTime >= shotCoolDown) {
            lastShotTime = Time.time;
            Vector3 dir1 = (moveRoute[(routeLoc + 1) % routeMax].position - moveRoute[routeLoc % routeMax].position).normalized;
            Vector3 dir2 = (moveRoute[mod ((routeLoc - 1), routeMax)].position - moveRoute[routeLoc % routeMax].position).normalized;

            shoot(dir1);
            shoot(dir2);
        }

        if (Time.time - lastMoveTime >= moveCoolDown) {
            lastMoveTime = Time.time;
            StartCoroutine(moveLocation(moveSpeed));
            }


    }

    private IEnumerator moveLocation(float time) {

        Vector3 start = moveRoute[routeLoc % routeMax].position;
        Vector3 end = moveRoute[(routeLoc + 1 ) % routeMax].position;

        float elapsedTime = 0;
        Vector3  pos = start;

        while ((elapsedTime / time) <= 1) {
            pos = Vector3.Lerp(start, end, (elapsedTime / time));


            transform.position = pos;

            elapsedTime += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }
        transform.position = end;
        routeLoc++;


    }

    //c# modulo deals with negatives differently because it is a remainder call
    //this fixes that
    private int mod(int x, int m) {
        return (x % m + m) % m;
    }


}
