using UnityEngine;
using System.Collections.Generic;
using System.Collections;

public class CameraScript : MonoBehaviour {

    List<Player> players = new List<Player>();

    [SerializeField] private float MaxDistance;
    Vector3 MidPoint;

    Vector3 Max;
    Vector3 Min;

    [SerializeField] private Vector3 offset;

    private float targetCameraSize;

    // Use this for initialization
    void Start () {
	    
	}
	
	// Update is called once per frame
	void Update () {
        if (players.Count > 0)
        {
            Max = players[0].transform.position;
            Min = players[0].transform.position;

            foreach (Player p in players)
            {
                if (Max.x < p.transform.position.x)
                {
                    Max.x = p.transform.position.x;
                }
                else if (Max.x > p.transform.position.x)
                {
                    Min.x = p.transform.position.x;
                }

                if (Max.y < p.transform.position.y)
                {
                    Max.y = p.transform.position.y;
                }
                else if (Max.y > p.transform.position.y)
                {
                    Min.y = p.transform.position.y;
                }

                if (Max.z < p.transform.position.z)
                {
                    Max.z = p.transform.position.z;
                }
                else if (Min.z > p.transform.position.z)
                {
                    Min.z = p.transform.position.z;
                }
            }

            MidPoint = (Min + Max) / 2;
            MidPoint.y = Mathf.Clamp(MidPoint.y, Max.y - MaxDistance, Max.y);
            MidPoint.x = 0.0f;
            transform.position = Vector3.MoveTowards(transform.position, MidPoint + offset, 22.0f * Time.deltaTime);

            targetCameraSize = Mathf.Clamp((Min - Max).magnitude, 4.0f, MaxDistance);

            if (Camera.main.orthographicSize > targetCameraSize)
            {
                Camera.main.orthographicSize += (Camera.main.orthographicSize - targetCameraSize) * Time.deltaTime * -2.0f;

            }
            else if (Camera.main.orthographicSize < targetCameraSize)
            {
                Camera.main.orthographicSize += (targetCameraSize - Camera.main.orthographicSize) * Time.deltaTime * 2.0f;
            }
        }
    }

    public void RegisterToCamera(Player playerToRegister)
    {
        players.Add(playerToRegister);
    }

    public void DeregisterFromCamera(Player playerToDeregister)
    {
        players.Remove(playerToDeregister);
    }
}
