using UnityEngine;
using System.Collections;

public class MouseOrbitC : MonoBehaviour {

	public Transform target;
	public float distance = 10.0f;
	
	public float xSpeed = 250.0f;
	public float ySpeed = 120.0f;
	
	public float yMinLimit = -20f;
	public float yMaxLimit = 80f;
	public float sensitivity = 4f;


	private float x = 0.0f;
	private float y = 0.0f;
	private Vector3 forward = Vector3.zero;

	CapsuleController CCscript;

	// Use this for initialization
	void Start () {
		var angles = transform.eulerAngles;
		x = angles.y;
		y = angles.x;


		CCscript = GameObject.Find("Capsule").GetComponent<CapsuleController>();
		// Make the rigid body not change rotation
	}
	
	// Update is called once per frame
	void LateUpdate () {
		if (target) {
			//get the zero angle from vector forward
			forward = CCscript.myForward;

			Debug.Log (forward);
			//float yRot = Input.GetAxis("Mouse X") * sensitivity

			x += Input.GetAxis("Mouse X") * sensitivity;
			y -= Input.GetAxis("Mouse Y") * sensitivity;
			
			y = ClampAngle(y, yMinLimit, yMaxLimit);
			
			Quaternion rotation = Quaternion.Euler(y, x, 0);
			Vector3 position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.position;

			transform.rotation = rotation;
			transform.position = position;
		}
	}

	float ClampAngle(float angle, float min, float max){
		if (angle < -360)
			angle += 360;
		if (angle > 360)
			angle -= 360;
		return Mathf.Clamp (angle, min, max);
	}
}