using UnityEngine;
using System.Collections;

public class CameraPan : MonoBehaviour {

    const float CAM_HEIGHT = 12.0f;
    public float PAN_SPEED = 35.0f;

    public Transform m_lockObject;

    public static CameraPan ms_instance;

    public static CameraPan Instance
    {
        get { return ms_instance; }
    }

    private Vector3 m_destPos;
    private bool m_lerp;
    private bool m_lerp_fast;

	// Use this for initialization
	void Start ()
    {
        if (ms_instance != null)
        {
            Debug.LogError("Only one camera allowed");
        }
        ms_instance = this;

//         Vector3 curPos = m_lockObject.position;
//         curPos.y = CAM_HEIGHT;
//         transform.position = curPos;
// 
//         transform.rotation = new Quaternion();
//         transform.Rotate(new Vector3(1.0f, 0.0f, 0.0f), 90.0f	
    }

	// Update is called once per frame
	void Update ()
    {
        if (!MenuSystem.InBattle)
        {
            transform.Translate(10000, 1000, 10000, Space.World);
            return;
        }
        else
        {
//             Vector3 curPos = m_lockObject.position;
//             curPos.y = CAM_HEIGHT;
//             transform.position = curPos;
// 
//             transform.rotation = new Quaternion();
//             transform.Rotate(new Vector3(1.0f, 0.0f, 0.0f), 90.0f);
        }

        float x = Input.GetAxis("Horizontal") * Time.deltaTime * PAN_SPEED;
        float y = Input.GetAxis("Vertical") * Time.deltaTime * PAN_SPEED;
        transform.Translate(x, 0, y, Space.World);

        if (Input.GetKeyDown( KeyCode.Space ) )
        {
            SnapToPlayer();
        }
        else if ( m_lerp )
        {
            Vector3 curPos = transform.position;

            if (Vector3.Distance(curPos, m_destPos) < 0.005f)
            {
                m_lerp = false;
                transform.position = m_destPos;
            }
            else
            {
                float lerpSpeed = m_lerp_fast ? 6.0f : 2.5f;

                Vector3 newPos = Vector3.Slerp(curPos, m_destPos, lerpSpeed * Time.deltaTime);
                newPos.y = CAM_HEIGHT;
                transform.position = newPos;
            }
        }
	}


    public void SnapToPlayer()
    {
        Vector3 curPos = m_lockObject.position;
        curPos.y = CAM_HEIGHT;
        transform.position = curPos;

        transform.rotation = new Quaternion();
        transform.Rotate(new Vector3(1.0f, 0.0f, 0.0f), 90.0f);


//         Vector3 curPos = transform.position;
//         curPos.x = m_lockObject.position.x;
//         curPos.z = m_lockObject.position.z;
//         transform.position = curPos;
        m_lerp = false;
    }

    public void MoveToPos(GridCoord pos, bool fast)
    {
        m_destPos = pos.GetUnityPos();
        m_destPos.y = transform.position.y;
        m_lerp = true;
        m_lerp_fast = fast;
    }
}
