using UnityEngine;
using System.Collections;

public class SecondaryCameraController : MonoBehaviour {

    public GameObject bassLoc;
    public GameObject guitarLoc;
    public GameObject drumsLoc;
    public GameObject keysLoc;
    public GameObject backOfHall;
    public GameObject bassPlayer;
    public GameObject guitarPlayer;
    public GameObject drumsPlayer;
    public GameObject keysPlayer;
    GameObject[] players = new GameObject[4];
    GameObject[] locations = new GameObject[5];
    public float distance = .3f;
    public float percentage = 0f;
    public float fraction = .1f;

    GameObject target;
    GameObject camTarget;
    GameObject previous;
    int itr = 1;
    public Camera cam1;
    public Camera cam2;
    //bool mainCam = false;

    // Use this for initialization
    void Start () {

        players[0] = bassPlayer;
        players[1] = guitarPlayer;
        players[2] = drumsPlayer;
        players[3] = keysPlayer;

        locations[0] = bassLoc;
        locations[1] = guitarLoc;
        locations[2] = drumsLoc;
        locations[3] = keysLoc;
        locations[4] = backOfHall;

        target = locations[1];
        previous = locations[0];
        camTarget = bassPlayer;
        
        cam1.enabled = false;
        cam2.enabled = true;
        Invoke("ChangeCam", 4.5f);
                   

    }
	
	// Update is called once per frame
	void Update () {

        target = locations[itr];
        if (Vector3.Distance(gameObject.transform.position, locations[itr].transform.position) < distance) {
            previous = target;
            percentage = 0;
            if (itr < 4) {
                itr++;                
            }else{
                itr = 0;
            }
        }
        lerpCamera();
        foreach (GameObject member in players)
        {
            if (Vector3.Distance(gameObject.transform.position, member.transform.position) < Vector3.Distance(gameObject.transform.position, camTarget.transform.position)) {
                camTarget = member;
            }
        }
        transform.LookAt(camTarget.transform.position);
        

    }

    void lerpCamera() {
        percentage += fraction;
        if (percentage < 1)
        {
            transform.position = Vector3.Lerp(previous.transform.position, target.transform.position, percentage);
        }
        else {
            percentage = 0;
        }

    }

    public void ChangeCam() {
        cam2.enabled = false;
        cam1.enabled = true;
    }
}
