using UnityEngine;
using System.Collections;

public class CameraRig : MonoBehaviour {

    public Transform m_camera = null;
    public Transform m_yTransform = null;
    public Transform m_lookAt = null;
    public Transform m_follow = null;
    public float m_ySpeed = 1.0f;
    public float m_xSpeed = 1.0f;
    public float m_minHeight = 1.0f;
    public float m_maxHeight = 5.0f;
    private Vector3 m_offset = Vector3.zero;
    private Quaternion m_previousRotationY = Quaternion.identity;

	void Start( ) {
        m_offset = transform.position - m_follow.position;
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
	}

	public void update( ) {

        if ( Input.GetKeyDown( KeyCode.P ) ) {

            if ( Cursor.lockState != CursorLockMode.Locked ) {
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible = false;
            } else {
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = true;
            }
        }

        if ( Input.GetKeyDown( KeyCode.I ) ) {
            m_ySpeed += 0.25f;
        }

        if ( Input.GetKeyDown( KeyCode.K ) ) {
            m_ySpeed -= 0.25f;
        }

        if ( Input.GetKeyDown( KeyCode.J ) ) {
            m_xSpeed -= 0.25f;
        }

        if ( Input.GetKeyDown( KeyCode.L ) ) {
            m_xSpeed += 0.25f;
        }

        m_previousRotationY = m_yTransform.rotation;

        Vector3 mouseMovement = Vector3.zero;
        mouseMovement.x = Input.GetAxis( "Mouse X" ) * m_xSpeed;
        mouseMovement.y = Input.GetAxis( "Mouse Y" ) * m_ySpeed * -1.0f;
        m_yTransform.Rotate( mouseMovement.y, 0.0f, 0.0f );

        if ( m_camera.position.y <= m_minHeight || m_camera.position.y >= m_maxHeight ) {
            m_yTransform.rotation = m_previousRotationY;
        }

        transform.Rotate( 0.0f, mouseMovement.x, 0.0f );

        transform.position = m_follow.transform.position + m_offset;
        m_camera.transform.LookAt( m_lookAt );
	}
}
