using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

	Vector3 lastMousePosition;
	Vector3 focusPoint;
	float distanceToFocusPoint;
	public Vector2 distanceRange;
	public float movementSpeed;
	public float rotationSpeed;
	public float distanceSpeed;
	float yawAngle;
	float pitchAngle;

	public bool allowMovement;

	public Camera Cam
	{
		get
		{
			return Camera.main;
		}
	}
	public Transform CamT
	{
		get
		{
			return Camera.main.transform;
		}
	}

	void OnEnable()
	{
		lastMousePosition = Input.mousePosition;
	}

	void Awake()
	{
		var ray = Cam.ScreenPointToRay(new Vector2(Screen.width * 0.5f, Screen.height * 0.5f));
		RaycastHit hit;
		if(Physics.Raycast(ray, out hit))
		{
			focusPoint = hit.point;
		}
		else
		{
			focusPoint = Vector3.zero;
		}
		distanceToFocusPoint = Vector3.Distance(CamT.position, focusPoint);
		var xzPosition = new Vector2(CamT.position.x, CamT.position.z) - new Vector2(focusPoint.x, focusPoint.z);
		var xzDirection = xzPosition.normalized;
		yawAngle = Mathf.Atan2(xzDirection.y, xzDirection.x);
		pitchAngle = Mathf.Acos((CamT.position.y - focusPoint.y) / distanceToFocusPoint);
	}

	void Update()
	{
		if(allowMovement)
		{
			distanceToFocusPoint = Mathf.Clamp(distanceToFocusPoint - Input.mouseScrollDelta.y * distanceSpeed, distanceRange.x, distanceRange.y);
			var forward = CamT.forward;
			forward.y = 0f;
			forward.Normalize();
			var movement = (CamT.right * Input.GetAxis("Horizontal") + forward * Input.GetAxis("Vertical")) * movementSpeed * Time.deltaTime;
			focusPoint += movement;
			if(Input.GetMouseButton(0))
			{
				var mouseDelta = Input.mousePosition - lastMousePosition;
				yawAngle -= mouseDelta.x * rotationSpeed;
				pitchAngle = Mathf.Clamp(pitchAngle + mouseDelta.y * rotationSpeed, 0.1f, 89f);
			}
		}

		CamT.position = focusPoint + distanceToFocusPoint * new Vector3(Mathf.Cos(yawAngle) * Mathf.Sin(pitchAngle), Mathf.Cos(pitchAngle), Mathf.Sin(yawAngle) * Mathf.Sin(pitchAngle));
		CamT.LookAt(focusPoint);

		lastMousePosition = Input.mousePosition;
	}
}
