using UnityEngine;
using System.Collections;
using CorgiLabs.Utility;

public class CameraController : MonoBehaviour
{
    private Camera m_Camera;
    private Transform[] m_Targets = new Transform[2];

    private Vector3 m_LookPoint;
    private float m_Distance;

    [SerializeField] private float m_MinSize;
    [SerializeField] private float m_MaxSize;

    private void OnEnable()
    {
        EventManager.StartListening<PlayerController[]>(EventID.PlayersInstantiated, SetTargets);
    }

    private void OnDisable()
    {
        EventManager.StopListening<PlayerController[]>(EventID.PlayersInstantiated, SetTargets);
    }

    void Awake()
    {
        m_Camera = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        m_LookPoint = Vector3.Lerp(m_Targets[0].position, m_Targets[1].position, 0.5f);
        m_LookPoint.z = m_Camera.transform.position.z;
        m_Camera.transform.position = m_LookPoint;

        m_Distance = Vector3.Distance(m_Targets[0].position, m_Targets[1].position);
        if (m_Distance > (m_Camera.orthographicSize * 2))
        {
            m_Camera.orthographicSize = Mathf.Min(m_Camera.orthographicSize + 0.05f, m_MaxSize);
        }
        else if (m_Distance < (m_Camera.orthographicSize))
        {
            m_Camera.orthographicSize = Mathf.Max(m_Camera.orthographicSize - 0.05f, m_MinSize);
        }
    }

    private void SetTargets(PlayerController[] inPlayers)
    {
        for (int i = 0; i < 2; i++)
            m_Targets[i] = inPlayers[i].TransformComponent;
    }
}
