using UnityEngine;
using System.Collections;

public class ZoomBehaviour : MonoBehaviour 
{

    public GameObject Player1 = null;
    public GameObject Player2 = null;

    private Transform _Target = null;

    public float TimeToReach = 2f;
    public float MinSize = 5.5f;

    private float _ElapsedTime = 0.0f;

    private Vector3 _DefaultPosition;
    private float _DefaultSize = 0.0f;

	void Start ()
    {
        if(Player1 == null)
        {
            Player1 = GameObject.Find("Player1");
        }

        if (Player2 == null)
        {
            Player2 = GameObject.Find("Player2");
        }

        if (gameObject.camera != null)
        {
            _DefaultPosition = transform.position;
            _DefaultSize = gameObject.camera.orthographicSize;
        }
	}
	
	void Update () 
    {
        bool bPlayer1Charging = false;
        bool bPlayer2Charging = false;

        if (Player1 != null)
        {
            MegaShoot msp1 = (MegaShoot)Player1.GetComponent(typeof(MegaShoot));

            if (msp1 != null)
            {
                bPlayer1Charging = msp1.bPreparingShoot;
            }
        }

        if (Player2 != null)
        {
            MegaShoot msp2 = (MegaShoot)Player2.GetComponent(typeof(MegaShoot));

            if (msp2 != null)
            {
                bPlayer2Charging = msp2.bPreparingShoot;
            }
        }

        Transform target = null;

        if (bPlayer1Charging)
        {
            if (Player1 != null)
            {
                target = Player1.transform;
            }
        }
        else if (bPlayer2Charging)
        {
            if (Player2 != null)
            {
                target = Player2.transform;
            }
        }

        if (target != null)
        {
            if (target != _Target)
            {
                _ElapsedTime = 0f;
            }

            _ElapsedTime += Time.deltaTime;

            float percentage = _ElapsedTime / TimeToReach;
            Vector3 targetPos = Vector3.Lerp(transform.position, target.position, percentage);
            targetPos.z = transform.position.z;
            
            float power = 0f;

            MegaShoot ms = (MegaShoot) target.gameObject.GetComponent(typeof(MegaShoot));

            if (ms != null)
            {
                power = ms.Intensity;
            }

            float newSize = Mathf.Lerp(_DefaultSize, MinSize, power );
            gameObject.camera.orthographicSize = newSize;

            transform.position = targetPos;
        }
        else
        {
            _ElapsedTime = 0f;

            ResetCamera();
        }

        _Target = target;
	}
    
    private void ResetCamera()
    {
        transform.position = _DefaultPosition;
        gameObject.camera.orthographicSize = _DefaultSize;
    }
}
