using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

public class CameraController : MonoBehaviour {

    private Vector3 mouse_down_pos;
    private Vector3 cam_on_down;

    private Vector3 drag_up_vector;
    private Vector3 drag_right_vector;

    private float desired_size;

	// Use this for initialization
	void Start () {
        drag_right_vector = transform.right;
        drag_right_vector.y = 0;
        drag_right_vector.Normalize();

        drag_up_vector = transform.up;
        drag_up_vector.y = 0;
        drag_up_vector.Normalize();

        desired_size = Camera.main.orthographicSize;

	}


    bool down_in_correct_state = false;
	
	// Update is called once per frame
	void Update () {

        Camera.main.orthographicSize = Mathf.Lerp(
                Camera.main.orthographicSize, desired_size, Time.deltaTime * 3);

        Resolution current_res = Screen.currentResolution;
        float meters_to_pixels = (Camera.main.orthographicSize * 4) / current_res.height;


        if ( Input.GetMouseButtonDown(0) &&
                    EventSystem.current.currentSelectedGameObject == null )
            {
                cam_on_down = transform.position;
                mouse_down_pos = Input.mousePosition;
            }
        if ( Input.GetMouseButtonUp(0) ) down_in_correct_state = false;
        
        if ( TownManager.tm.current_state == PLAY_STATE.NORMAL )
        {
            if ( Input.GetMouseButtonDown(0) )
            {
                down_in_correct_state = true;
            }
            desired_size -= Input.GetAxis("Mouse ScrollWheel") * 5;
            desired_size = Mathf.Clamp(desired_size, 1, 15);

            if ( down_in_correct_state && 
                    EventSystem.current.currentSelectedGameObject == null )
            {
                Vector3 mouse_pos = Input.mousePosition;

                Vector3 diff = (mouse_pos - mouse_down_pos);

                diff = 
                    diff.x * drag_right_vector * meters_to_pixels + 
                    diff.y * drag_up_vector * meters_to_pixels;

                Vector3 new_pos = cam_on_down - diff;
                
                if (new_pos.x < -15 )
                {
                    new_pos.x = -15;
                }
                if (  new_pos.x > 40 )
                {
                    new_pos.x = 40;
                }
                if (new_pos.z < -15 )
                {
                    new_pos.z = -15;
                }
                if (  new_pos.z > 45 )
                {
                    new_pos.z = 45;
                }

                transform.position = new_pos;
            }
        }
	}
}
