using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(MazeAsset))]
public class MazeAssetCustomInspector : Editor
{
	private Material mat;

	private void OnEnable()
	{
		InitializeShader();
	}

	private void InitializeShader()
	{
		var shader = Shader.Find("Hidden/Internal-Colored");
		mat = new Material(shader);
	}

	private void OnDisable()
	{
		DestroyMaterial();
	}

	private void DestroyMaterial()
	{
		DestroyImmediate(mat);
	}

	public override void OnInspectorGUI()
	{
		DrawDefaultInspector();
		MazeAsset mazeAsset = (MazeAsset)target;

		if (GUILayout.Button("Update Maze"))
		{
			mazeAsset.UpdateMaze();
		}

		if(mazeAsset.GetMaze() != null && mazeAsset.GetMaze().GetRooms()!= null)
		{
			DebugMaze(mazeAsset.GetMaze());
		}
	}

	private void DebugMaze(Maze maze)
	{
		Rect rect = GUILayoutUtility.GetRect(10, 1000, 500, 500);
		if (Event.current.type == EventType.Repaint)
		{
			MazeRoom[] rooms = maze.GetRooms();

			Vector2 roomSize = GetRoomSize(rect, maze.GetMazeWidth(), maze.GetMazeHeight());

			GUI.BeginClip(rect);
			GL.PushMatrix();
			GL.Clear(true, false, Color.black);
			mat.SetPass(0);

			GL.Begin(GL.LINES);

			for(int y = 0; y < maze.GetMazeHeight(); y++)
			{
				for(int x = 0; x < maze.GetMazeWidth(); x++)
				{
					DebugRoom(rooms[maze.GetRoomIndex(x,y)], GetRoomOffset(roomSize, x, y), roomSize);
				}
			}

			GL.End();
			GUI.EndClip();

		}
	}

	private Vector2 GetRoomSize(Rect rect, int width, int height)
	{
		return new Vector2(rect.width / width, rect.height / height);
	}

	private Vector2 GetRoomOffset(Vector2 roomSize, int x, int y)
	{
		return new Vector2(roomSize.x * x, roomSize.y * y);
	}

	private void DebugRoom(MazeRoom mazeRoom, Vector2 roomOffset, Vector2 roomSize)
	{
		if(mazeRoom.IsActiveWall(MazeWallEnum.north))
		{
			GL.Vertex3(roomOffset.x, roomOffset.y + roomSize.y, 0f);
			GL.Vertex3(roomOffset.x + roomSize.x, roomOffset.y + roomSize.y, 0f);
		}

		if (mazeRoom.IsActiveWall(MazeWallEnum.south))
		{
			GL.Vertex3(roomOffset.x, roomOffset.y, 0f);
			GL.Vertex3(roomOffset.x + roomSize.x, roomOffset.y, 0f);
		}

		if (mazeRoom.IsActiveWall(MazeWallEnum.east))
		{
			GL.Vertex3(roomOffset.x, roomOffset.y, 0f);
			GL.Vertex3(roomOffset.x, roomOffset.y + roomSize.y, 0f);
		}

		if (mazeRoom.IsActiveWall(MazeWallEnum.west))
		{
			GL.Vertex3(roomOffset.x + roomSize.x, roomOffset.y, 0f);
			GL.Vertex3(roomOffset.x + roomSize.x, roomOffset.y + roomSize.y, 0f);
		}
	}
}
