using UnityEngine;
using System;
using System.Collections;

public class Draggable : MonoBehavclops
{

	public event Action DidStartDragging;
	public event Action DidStopDragging;

	public Transform transformToDrag;
	
	private bool _isDragging;
	private Vector2 _mouseOffset;
	private Vector2 _startPos;
	private bool _isDown;

	public void Awake()
	{
		if (transformToDrag == null) transformToDrag = transform;
	}

	public void OnMouseDown()
	{
		_isDown = true;
		_startPos = MouseWorldPosition;
	}

	public void OnMouseUp()
	{
		_isDown = false;
		if (!_isDragging) return;
		_isDragging = false;
		if (DidStopDragging != null) DidStopDragging();
	}

	public void Update()
	{
		if (!_isDragging) {
			if (_isDown && (MouseWorldPosition - _startPos).magnitude > 0.2f) {
				if (DidStartDragging != null) DidStartDragging();
				_isDragging = true;
				_mouseOffset = (Vector2)transformToDrag.position - MouseWorldPosition;
			}
		} else {
			transformToDrag.position = (Vector3)(MouseWorldPosition + _mouseOffset);
		}
	}

	private Vector2 MouseWorldPosition
	{
		get
		{
			return (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
		}
	}

}
