using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class MovableObject : MonoBehaviour
{
	private void Update()
	{
		InitializeGrabAreaIfNeeded();
	}

	#region Grab Area

	private static readonly string GrabAreaGameObjectName = "MovableObjectGrabArea";
	private int GrabMessageId;
	public float GrabRadius = 3f;

	[SerializeField]
	[HideInInspector]
	private SphereCollider GrabArea;

	private void InitializeGrabAreaIfNeeded()
	{
		if (GrabArea == null)
		{
			var grabAreaTransform = transform.FindChild(GrabAreaGameObjectName);
			if (grabAreaTransform == null)
			{
				var grabAreaGO = new GameObject(GrabAreaGameObjectName) as GameObject;
				grabAreaGO.transform.parent = transform;
				grabAreaGO.transform.localPosition = Vector3.zero;
				GrabArea = grabAreaGO.AddComponent<SphereCollider>();
				GrabArea.isTrigger = true;
				var proxy = grabAreaGO.AddComponent<TriggerProxy>();
				proxy.target = gameObject;
			}
			else
			{
				GrabArea = grabAreaTransform.GetComponent<SphereCollider>();
			}
		}

		if (GrabArea.radius != GrabRadius)
		{
			GrabArea.radius = GrabRadius;
		}
	}

	private void OnTriggerEnter(Collider other)
	{
		GrabMessageId = ScreenNotification.Instance.Show("Press space to grab", 0f);
	}

	private void OnTriggerExit(Collider other)
	{
		ScreenNotification.Instance.Hide(GrabMessageId);
	}

	#endregion
}
