
using UnityEditor;
using UnityEngine;
using System.Collections;


[CustomEditor(typeof(Tile))]
public class TileEditor : Editor
{

	override public void OnInspectorGUI() 
	{
		//Tile component = (Tile)target;
		//Component. = EditorGUILayout.Toggle("Paint Tiles Enabled",m_placeTiles);
		base.OnInspectorGUI();
	}

	void OnSceneGUI() 
	{


		
		if ( Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag )
		{
			Tile component = (Tile)target;
			if ( component == null || component.m_tilePaintingEnabled == false )
				return;

			if ( Event.current.button == 0 )
			{
				Event.current.Use();
				//Debug.Log("Mousedown");
				//Tile component = (Tile)target;
				Vector2 pos = (Vector2)HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin;
				pos = Utils.Snap(pos+new Vector2(component.size/2,component.size/2),component.size) - new Vector2(component.size/2,component.size/2);
				if ( Physics2D.BoxCast(pos,new Vector2(component.size-0.1f, component.size-0.1f),0,Vector2.zero,0) == false )
				{
					// get prefab
					GameObject toSpawn = PrefabUtility.GetPrefabParent(component.gameObject) as GameObject;
					if ( toSpawn == null )
						return;
						//toSpawn = component.gameObject;
                    GameObject obj = PrefabUtility.InstantiatePrefab(toSpawn) as GameObject;

                    obj.transform.position = pos;
					obj.name = toSpawn.name;
					GameObject levelFolder = GameObject.Find("Level"); // nest under object named "Level" if found
					obj.transform.parent = levelFolder == null ? component.transform.parent : levelFolder.transform;
					obj.transform.position = pos;
				}
			}
			else if ( Event.current.button == 1 )
			{
				//Tile component = (Tile)target;
				Event.current.Use();
				Vector2 pos = (Vector2)HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin;				

				RaycastHit2D hit = Physics2D.Raycast(pos,Vector2.one,1, 1<<(int)eLayers.eGround | 1<<(int)eLayers.eTrigger );
				if ( hit.transform != null )
					GameObject.DestroyImmediate(hit.transform.gameObject);
			}
		}

		if (Event.current.type == EventType.Layout ) 
		{			
			if ( Event.current.button == 0 /*|| Event.current.button == 1*/ )
			{

				Tile component = (Tile)target;
				if ( component == null || component.m_tilePaintingEnabled == false )
					return;
				HandleUtility.AddDefaultControl(0);
				// Debug.Log("layout");
			}
		}
	}

}
