using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using UnityEditor.IMGUI.Controls;

[CustomEditor(typeof(Entity))]
public class EntityEditor : Editor
{
	void Marker(ref float x, ref float y, string label) {
		Vector2 pos = new Vector2(x, y);
		pos = Handles.Slider2D(pos, Vector3.forward, Vector3.right, Vector3.up, 0.1f, Handles.RectangleHandleCap, 1.0f);
		Handles.Label(new Vector3(pos.x, pos.y, 0), label);
		x = pos.x;
		y = pos.y;
	}

	Rect EditRect(string label, Rect rect, Color color, float alpha) {
		Color maincolor = new Color(color.r, color.g, color.b, alpha);

		var old = Handles.zTest;
		Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
		Handles.DrawSolidRectangleWithOutline(rect, maincolor, color);
		Handles.zTest = old;

		float x0 = rect.xMin, y0 = rect.yMin, x1 = rect.xMax, y1 = rect.yMax;
		Marker(ref x0, ref y0, label);
		Marker(ref x1, ref y0, label);
		Marker(ref x0, ref y1, label);
		Marker(ref x1, ref y1, label);
		rect.xMin = x0;
		rect.yMin = y0;
		rect.xMax = x1;
		rect.yMax = y1;
		return rect;
	}

	protected virtual void OnSceneGUI() {
		if (!target)
			return;

		Entity ent = target as Entity;

		Matrix4x4 mtx = Matrix4x4.LookAt(
			ent.transform.position + ent.transform.up*0.01f,
			ent.transform.position - ent.transform.up,
			ent.transform.forward);

		using (new Handles.DrawingScope(mtx)) {
			EditorGUI.BeginChangeCheck();

			Rect newvision = EditRect("Vision", ent.vision, Color.red, 0.1f);
			Rect newuse = EditRect("Usable", ent.useRange, Color.green, 0.1f);
			Rect newhome = EditRect("Home", ent.home, Color.blue, 0.1f);

			if (EditorGUI.EndChangeCheck()) {
				Undo.RecordObject(ent, "Change Region");
				ent.vision = newvision;
				ent.useRange = newuse;
				ent.home = newhome;
			}
		}
	}

	public override void OnInspectorGUI() {
		if (!target)
			return;

		Entity ent = target as Entity;

		DrawDefaultInspector();

		if (EditorApplication.isPlaying) {
			GUILayout.BeginVertical(EditorStyles.helpBox);
			EditorGUILayout.LabelField("Actions:");
			EntityBehaviour[] actions = ent.GetActions();
			if (actions.Length == 0) {
				EditorGUILayout.LabelField("   <none>");
			} else {
				foreach (EntityBehaviour action in actions) {
					string name = action.GetType().Name;
					if (action.enabled)
						EditorGUILayout.LabelField($"   {name}");
					else
						EditorGUILayout.LabelField($"   {name} (paused)");
				}
			}
			GUILayout.EndVertical();
		}
	}
}
