// Credit to damien_oconnell from http://forum.unity3d.com/threads/39513-Click-drag-camera-movement
// for using the mouse displacement for calculating the amount of camera movement and panning code.

using UnityEngine;
using System.Collections;

public class MoveCamera : MonoBehaviour {
    //
    // VARIABLES
    //

    public float turnSpeed = 4.0f;  // Speed of camera turning when mouse moves in along an axis
    public float panSpeed = 4.0f;   // Speed of the camera when being panned
    public float zoomSpeed = 4.0f;  // Speed of the camera going back and forth

    private Vector3 mouseOrigin;  // Position of cursor when mouse dragging starts
    private bool isPanning;       // Is the camera being panned?
    private bool isRotating;      // Is the camera being rotated?
    private bool isZooming;       // Is the camera zooming?

    //
    // UPDATE
    //

    void Update() {
        // Get the left mouse button
        if (GameInput.PrimaryPointerPressedThisFrame()) {
            // Get mouse origin
            mouseOrigin = GameInput.PointerPosition();
            isRotating = true;
        }

        // Get the right mouse button
        if (GameInput.SecondaryPointerPressedThisFrame()) {
            // Get mouse origin
            mouseOrigin = GameInput.PointerPosition();
            isPanning = true;
        }

        // Get the middle mouse button
        if (GameInput.MiddlePointerPressedThisFrame()) {
            // Get mouse origin
            mouseOrigin = GameInput.PointerPosition();
            isZooming = true;
        }

        // Disable movements on button release
        if (!GameInput.PrimaryPointerPressed()) isRotating = false;
        if (!GameInput.SecondaryPointerPressed()) isPanning = false;
        if (!GameInput.MiddlePointerPressed()) isZooming = false;

        // Rotate camera along X and Y axis
        if (isRotating) {
            Vector3 pos = Camera.main.ScreenToViewportPoint(
                    (Vector3)GameInput.PointerPosition() - mouseOrigin);

            transform.RotateAround(transform.position, transform.right, -pos.y * turnSpeed);
            transform.RotateAround(transform.position, Vector3.up, pos.x * turnSpeed);
        }

        // Move the camera on it's XY plane
        if (isPanning) {
            Vector3 pos = Camera.main.ScreenToViewportPoint(
                    (Vector3)GameInput.PointerPosition() - mouseOrigin);

            Vector3 move = new Vector3(pos.x * panSpeed, pos.y * panSpeed, 0);
            transform.Translate(move, Space.Self);
        }

        // Move the camera linearly along Z axis
        if (isZooming) {
            Vector3 pos = Camera.main.ScreenToViewportPoint(
                    (Vector3)GameInput.PointerPosition() - mouseOrigin);

            Vector3 move = pos.y * zoomSpeed * transform.forward;
            transform.Translate(move, Space.World);
        }
    }
}
