import UnityEditor;
import System.IO;

@CustomEditor(Grid)
class TileEditor extends Editor
{
 var object : GameObject;
 var grid : Grid;
 private var threeDOn : boolean = false;
 private var threeDOff : boolean = true;
 private var selectedTile : int = 0;
 private var selectedTileStrings : String[] = ["1","2","3","4","5","6","7","8","9"];
 private var selectedItem : int = 0;
 private var selectedItemStrings : String[] = ["1","2","3","4","5","6"];
 
 
 
 function OnEnable()
 {
  grid = target as Grid;
  SceneView.onSceneGUIDelegate = GridUpdate;
 }
 
 function GridUpdate(sceneView : SceneView)
 {
  var event : Event = Event.current;
  var ray : Ray = Camera.current.ScreenPointToRay(Vector3(event.mousePosition.x,-event.mousePosition.y+Camera.current.pixelHeight));
  var mousePos : Vector3 = ray.origin;
  
  if(threeDOn)
  {
   threeDOff = false;
   grid.color = Color.cyan;
   grid.colorD = Color.red;
  }
  else if(threeDOff)
  {
   threeDOn = false;
   grid.color = Color(0.5,0.5,0.5,0.5);
   grid.colorD = Color.clear;
  }
  
  if (event.isKey && event.character == 'a')
  {
   switch(selectedTile)
   {
    case 0 :
     object = Settings.setTile1;
	case 1 :
	 object = Settings.setTile2;                 
   }
   object = EditorUtility.InstantiatePrefab(object) as GameObject;
   var aligned : Vector3 = Vector3((Mathf.Floor(mousePos.x/grid.gridWidth)*grid.gridWidth+grid.gridWidth/2),(Mathf.Floor(mousePos.y/grid.gridHeight)*grid.gridHeight+grid.gridHeight/2),0);
   object.transform.position = aligned;
  }
  else if(event.isKey&&event.character == 'w')
  {
   switch(selectedItem)
   {
    case 0 :
     object = Settings.setItem1;
	case 1 :
	 object = Settings.setItem2;
   }
   object = EditorUtility.InstantiatePrefab(object) as GameObject;
   var unAligned : Vector3 = Vector3(mousePos.x,mousePos.y,0);
   object.transform.position = unAligned;
  }
  else if(event.isKey && event.character == 'd')
  {
   for (var object : GameObject in Selection.gameObjects)
   {
    DestroyImmediate(object);
   }
  }
 }
 
 function OnInspectorGUI()
 {
  GUILayout.BeginHorizontal();
  GUILayout.Label("Grid with");
  grid.gridWidth = EditorGUILayout.FloatField(grid.gridWidth,GUILayout.Width(50));
  GUILayout.EndHorizontal();
  
  GUILayout.BeginHorizontal();
  GUILayout.Label("Grid height");
  grid.gridHeight = EditorGUILayout.FloatField(grid.gridHeight,GUILayout.Width(50));
  GUILayout.EndHorizontal();
  
  GUILayout.BeginHorizontal();
  threeDOn = GUILayout.Button("3D-Mode(on)");
  threeDOff = GUILayout.Button("3D-Mode(off)");
  GUILayout.EndHorizontal();
  
  GUILayout.Space(75);
  GUILayout.Label("Tiles");
  
  GUILayout.BeginHorizontal();
  selectedTile = GUILayout.SelectionGrid(selectedTile,selectedTileStrings,3);
  GUILayout.EndHorizontal();
  
  GUILayout.Space(25);
  GUILayout.Label("Items");
  
  GUILayout.BeginHorizontal();
  selectedItem = GUILayout.SelectionGrid(selectedItem,selectedItemStrings,3);
  GUILayout.EndHorizontal();

  SceneView.RepaintAll();
 }
 
}