using UnityEngine;
using System.Collections;
using ChunkRendering;
 
 
public class CameraBehaviour : MonoBehaviour {

	public float sensitivityX = 8F;
	public float sensitivityY = 8F;

	float mHdg = 0F;
	float mPitch = 0F;

	private float accumulator; 

	void Start()
	{
	// owt?
	}

	void Update()
	{
		if (!(Input.GetMouseButton(0) || Input.GetMouseButton(1)))
		return;

		float deltaX = Input.GetAxis("Mouse X") * sensitivityX;
		float deltaY = Input.GetAxis("Mouse Y") * sensitivityY;

		if (Input.GetMouseButton(0) && Input.GetMouseButton(1))
		{
			Strafe(deltaX);
			ChangeHeight(deltaY);
		}
		else
		
			if (Input.GetMouseButton(0))
			{
				MoveForwards(deltaY);
				ChangeHeading(deltaX);
			}
			else if (Input.GetMouseButton(1))
			{
				ChangeHeading(deltaX);
				ChangePitch(-deltaY);
			}
		}
		
		/*accumulator += Time.deltaTime;
		
		if(accumulator >= 1.0f)
		{	
			RaycastHit hit;
			Ray ray = camera.ScreenPointToRay (new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
			Physics.Raycast(ray, out hit, 512);
			
			if(hit.collider != null)
			{
				GameObject gameObj = hit.collider.gameObject;
				gameObj.GetComponent("ChunkBehaviour")
			}
		}*/
	}

	void MoveForwards(float aVal)
	{
		Vector3 fwd = transform.forward;
		fwd.y = 0;
		fwd.Normalize();
		transform.position += aVal * fwd;
	}

	void Strafe(float aVal)
	{
		transform.position += aVal * transform.right;
	}

	void ChangeHeight(float aVal)
	{
		transform.position += aVal * Vector3.up;
	}

	void ChangeHeading(float aVal)
	{
		mHdg += aVal;
		WrapAngle(ref mHdg);
		transform.localEulerAngles = new Vector3(mPitch, mHdg, 0);
	}

	void ChangePitch(float aVal)
	{
		mPitch += aVal;
		WrapAngle(ref mPitch);
		transform.localEulerAngles = new Vector3(mPitch, mHdg, 0);
	}

	public static void WrapAngle(ref float angle)
	{
		if (angle < -360F)
			angle += 360F;
		if (angle > 360F)
			angle -= 360F;
	}
}
