using UnityEngine;
using System.Collections;
/**
 * Author: Nick Edwards
 */
public class CameraController : MonoBehaviour {

	private const float OLD_POS = 0.9f;
	private const float NEW_POS = 1f - OLD_POS;
	private float cameraHeight;
	public float MAX_TURN = 8f;
	public float MAX_DELTA_HEIGHT = 20f;
	public float MAX_ANGLE_RATE = 0.05f;
	private float baseVerticalPosition;
	public float OFFSET = 1.1f;
	private float zOffset;

	public Transform target, player, rotationTarget, lookTarget;
	// Use this for initialization
	void Start() {
		cameraHeight = transform.position.y;
		baseVerticalPosition = transform.position.y;
		zOffset = 0;
	}

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

		handleVertical();

		transform.position = new Vector3(transform.position.x, cameraHeight, transform.position.z);
		//Vector3 where = transform.position * OLD_POS + targetPos * NEW_POS;
		//transform.position = ((where - target.position).sqrMagnitude < 0.0001f ? target.position : where);
		handleRotation();
	}

	private void handleVertical() {
		//Debug.Log(zOffset);
		if (Input.GetAxis("Tilt") > 0f) {
			if (cameraHeight < baseVerticalPosition + MAX_DELTA_HEIGHT) {
				cameraHeight += MAX_ANGLE_RATE;
				zOffset += OFFSET;
				//transform.LookAt(player);
			}
		}
		else if (Input.GetAxis("Tilt") < 0f) {
			if (cameraHeight > baseVerticalPosition) {
				cameraHeight -= MAX_ANGLE_RATE;
				zOffset -= OFFSET;
				//transform.LookAt(player);
			}
		}
	}

	private void handleRotation() {
		Quaternion initial = transform.rotation;
		transform.LookAt(lookTarget.position + (lookTarget.forward * zOffset));
		Quaternion final = transform.rotation;
		transform.rotation = Quaternion.Slerp(initial, final, MAX_TURN * Time.deltaTime);
	}

}
