#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
using UnityEngine;
using System;

public class DebugEditor 
{
	const string debugMethod = "GameDebug:Log";
	const string debugCS = "GameDebug.cs";

	[UnityEditor.Callbacks.OnOpenAssetAttribute(0)]
	static bool OnClickConsole (int instanceID, int line)
	{
		string stackTrace = GetStackTrace();
		if (!string.IsNullOrEmpty(stackTrace) && stackTrace.Contains(debugMethod))
		{
			Match mathes = Regex.Match(stackTrace, @"\(at (.+)\)", RegexOptions.IgnoreCase);
			string pathLine = "";
			while(mathes.Success)
			{
				pathLine = mathes.Groups[1].Value;
				if (!pathLine.Contains(debugCS))
				{
					int splitIndex = pathLine.LastIndexOf(":");
					string path = pathLine.Substring(0, splitIndex);
					line = System.Convert.ToInt32(pathLine.Substring(splitIndex + 1));
					if (line < 0) continue;

					string fullPath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/Assets"));
					fullPath = Path.Combine(fullPath, path);
					UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(fullPath, line);
					return true;
				}
				mathes = mathes.NextMatch();
			}
		}

		return false;
	}

	static string GetStackTrace ()
	{
		Type consoleWindowType = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
		FieldInfo fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
		object consoleWindowInstance = fieldInfo.GetValue(null);
		if (consoleWindowInstance != null)
		{
			if ((object )EditorWindow.focusedWindow == consoleWindowInstance)
			{
				Type listViewStateType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ListViewState");
				fieldInfo = consoleWindowType.GetField("m_ListView", BindingFlags.NonPublic | BindingFlags.Instance);
				object listView = fieldInfo.GetValue(consoleWindowInstance);
				fieldInfo =	listViewStateType.GetField("row", BindingFlags.Instance | BindingFlags.Public);
				int row = (int)fieldInfo.GetValue(listView);
				fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
				string activeText = fieldInfo.GetValue(consoleWindowInstance).ToString();
				return activeText;
			}
		}

		return null;
	}
}

#endif