using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

	public static Camera cam;
	public static PlayerController player;
	public float speed; 
	public float speedupMult;
	
	private static Vector2 offset; 
	private static float origZoom;
	private static float targZoom;

	private Vector3 targetpos;
	private float newX, newY;

	// Use this for initialization
	void Start () {
		cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
		origZoom = cam.transform.position.z;
		Debug.Log(origZoom);
	}
	
	
	void FixedUpdate () 
	{	
		targetpos = player.transform.position + (Vector3)offset;  
	
		Vector2 diff = targetpos - transform.position;
		Vector2 norm = diff.normalized * speed * Time.fixedDeltaTime;
		
		if (Mathf.Abs (diff.x) < Mathf.Abs (norm.x) || Mathf.Abs (diff.y) < Mathf.Abs (norm.y)) {
			newX = targetpos.x;
			newY = targetpos.y;
			
		} else if (diff.magnitude >= speedupMult * norm.magnitude){
			newX = transform.position.x + diff.x / speedupMult;
			newY = transform.position.y + diff.y / speedupMult;
			
		} else {
			newX = transform.position.x + norm.x;
			newY = transform.position.y + norm.y;
		}
		
		transform.position = new Vector3(newX, newY, (transform.position.z*7 + targZoom) / 8);
 
	}

	public static void SetOffset(Vector2 off){
		offset = off;
	}
	 
	public static void SetZoom(float zoomRatio){
		if (cam==null) {
			cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>(); 
			origZoom = cam.transform.position.z;
		}
		targZoom = origZoom * zoomRatio; 
	}

	public static void SetFollowTarget(PlayerController nex){
		player = nex;
	}
}  