using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.NET.Common;
using BepInExResoniteShim;
using HarmonyLib;
using MonkeyLoader;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0")]
[assembly: AssemblyCompany("Nytra")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+8b9404036e18e3881c94340d1607cea6fc7e046b")]
[assembly: AssemblyProduct("MonkeyLoaderLoader")]
[assembly: AssemblyTitle("MonkeyLoaderLoader")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Nytra/MonkeyLoaderLoader-BepInEx")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace MonkeyLoaderLoader.BepInEx;
[HarmonyPatch(typeof(AssemblyLoadContextLoadStrategy), "LoadFile")]
internal class MonkeyLoaderPatch
{
	private static bool Prefix(string assemblyPath, ref Assembly __result)
	{
		string assemblyPath2 = assemblyPath;
		string name = Path.GetFileNameWithoutExtension(assemblyPath2);
		if (name == "Resonite")
		{
			return false;
		}
		Assembly val = Enumerable.FirstOrDefault<Assembly>((global::System.Collections.Generic.IEnumerable<Assembly>)AppDomain.CurrentDomain.GetAssemblies(), (Func<Assembly, bool>)((Assembly a) => a.Location == assemblyPath2 || a.GetName().Name == name));
		if (val != (Assembly)null)
		{
			__result = val;
			return false;
		}
		return true;
	}
}
internal class MonkeyLoaderWrapperPatch
{
	public class ExplodeException : global::System.Exception
	{
		public ExplodeException(string msg)
			: base(msg)
		{
		}
	}
	[CompilerGenerated]
	private sealed class <Transpiler>d__7 : global::System.Collections.Generic.IEnumerable<CodeInstruction>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<CodeInstruction>, global::System.Collections.IEnumerator, global::System.IDisposable
	{
		private int <>1__state;
		private CodeInstruction <>2__current;
		private int <>l__initialThreadId;
		private global::System.Collections.Generic.IEnumerable<CodeInstruction> instructions;
		public global::System.Collections.Generic.IEnumerable<CodeInstruction> <>3__instructions;
		private CodeInstruction[] <instArr>5__2;
		private int <i>5__3;
		CodeInstruction global::System.Collections.Generic.IEnumerator<CodeInstruction>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}
		object global::System.Collections.IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}
		[DebuggerHidden]
		public <Transpiler>d__7(int <>1__state)
		{
			this.<>1__state = <>1__state;
			<>l__initialThreadId = Environment.CurrentManagedThreadId;
		}
		[DebuggerHidden]
		void global::System.IDisposable.Dispose()
		{
			<instArr>5__2 = null;
			<>1__state = -2;
		}
		private bool MoveNext()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<instArr>5__2 = Enumerable.ToArray<CodeInstruction>(instructions);
				<i>5__3 = 0;
				break;
			case 1:
				<>1__state = -1;
				<>2__current = new CodeInstruction(OpCodes.Call, (object)_explodeMethod);
				<>1__state = 2;
				return true;
			case 2:
				<>1__state = -1;
				goto IL_010b;
			case 3:
				<>1__state = -1;
				goto IL_010b;
			case 4:
				{
					<>1__state = -1;
					goto IL_010b;
				}
				IL_010b:
				<i>5__3++;
				break;
			}
			if (<i>5__3 < <instArr>5__2.Length)
			{
				CodeInstruction val = <instArr>5__2[<i>5__3];
				if (CodeInstructionExtensions.Calls(val, _invokeMethod) && <instArr>5__2[<i>5__3 - 1].opcode == OpCodes.Ldnull)
				{
					<>2__current = val;
					<>1__state = 1;
					return true;
				}
				if (CodeInstructionExtensions.Calls(val, _loadFromAssemblyPathMethodOriginal))
				{
					<>2__current = new CodeInstruction(OpCodes.Call, (object)_loadFromAssemblyPathMethodReplacement);
					<>1__state = 3;
					return true;
				}
				<>2__current = val;
				<>1__state = 4;
				return true;
			}
			return false;
		}
		bool global::System.Collections.IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}
		[DebuggerHidden]
		void global::System.Collections.IEnumerator.Reset()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new NotSupportedException();
		}
		[DebuggerHidden]
		global::System.Collections.Generic.IEnumerator<CodeInstruction> global::System.Collections.Generic.IEnumerable<CodeInstruction>.GetEnumerator()
		{
			<Transpiler>d__7 <Transpiler>d__;
			if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
			{
				<>1__state = 0;
				<Transpiler>d__ = this;
			}
			else
			{
				<Transpiler>d__ = new <Transpiler>d__7(0);
			}
			<Transpiler>d__.instructions = <>3__instructions;
			return <Transpiler>d__;
		}
		[DebuggerHidden]
		global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
		{
			return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<CodeInstruction>)this).GetEnumerator();
		}
	}
	private static readonly MethodInfo _invokeMethod = AccessTools.Method(typeof(MethodBase), "Invoke", new global::System.Type[2]
	{
		typeof(object),
		typeof(object[])
	}, (global::System.Type[])null);
	private static readonly MethodInfo _loadFromAssemblyPathMethodOriginal = AccessTools.Method(typeof(AssemblyLoadContext), "LoadFromAssemblyPath", (global::System.Type[])null, (global::System.Type[])null);
	private static readonly MethodInfo _loadFromAssemblyPathMethodReplacement = AccessTools.Method(typeof(MonkeyLoaderWrapperPatch), "LoadFromAssemblyPath", (global::System.Type[])null, (global::System.Type[])null);
	private static readonly MethodInfo _explodeMethod = AccessTools.Method(typeof(MonkeyLoaderWrapperPatch), "Explode", (global::System.Type[])null, (global::System.Type[])null);
	private static Assembly LoadFromAssemblyPath(AssemblyLoadContext alc, string assemblyPath)
	{
		string assemblyPath2 = assemblyPath;
		string name = Path.GetFileNameWithoutExtension(assemblyPath2);
		Assembly val = Enumerable.FirstOrDefault<Assembly>((global::System.Collections.Generic.IEnumerable<Assembly>)AppDomain.CurrentDomain.GetAssemblies(), (Func<Assembly, bool>)((Assembly a) => a.Location == assemblyPath2 || a.GetName().Name == name));
		if (val != (Assembly)null)
		{
			return val;
		}
		return alc.LoadFromAssemblyPath(assemblyPath2);
	}
	private static void Explode()
	{
		throw new ExplodeException("I couldn't figure out a better way to stop MonkeyLoaderWrapper from starting Resonite...");
	}
	[IteratorStateMachine(typeof(<Transpiler>d__7))]
	public static global::System.Collections.Generic.IEnumerable<CodeInstruction> Transpiler(global::System.Collections.Generic.IEnumerable<CodeInstruction> instructions)
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <Transpiler>d__7(-2)
		{
			<>3__instructions = instructions
		};
	}
}
internal class MonkeyLoaderLoader
{
	private static readonly FileInfo _monkeyLoaderWrapperPath = new FileInfo("MonkeyLoaderWrapper.dll");
	private static Assembly? _monkeyLoaderWrapperAsm;
	private static MethodInfo? _resolveNativeLibraryMethod;
	private static void PreloadAssemblies()
	{
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Expected O, but got Unknown
		_monkeyLoaderWrapperAsm = Assembly.LoadFrom(((FileSystemInfo)_monkeyLoaderWrapperPath).FullName);
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		global::System.Collections.Generic.IEnumerator<string> enumerator = Enumerable.Where<string>((global::System.Collections.Generic.IEnumerable<string>)Directory.GetFiles("MonkeyLoader"), (Func<string, bool>)((string f) => f.EndsWith(".dll"))).GetEnumerator();
		try
		{
			bool flag = default(bool);
			while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
			{
				string current = enumerator.Current;
				string name = Path.GetFileNameWithoutExtension(current);
				if (!Enumerable.Any<Assembly>((global::System.Collections.Generic.IEnumerable<Assembly>)assemblies, (Func<Assembly, bool>)((Assembly a) => a.GetName().Name == name)))
				{
					ManualLogSource? log = Plugin.Log;
					BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(12, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Preloading: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name);
					}
					log.LogDebug(val);
					Assembly.LoadFrom(current);
				}
			}
		}
		finally
		{
			((global::System.IDisposable)enumerator)?.Dispose();
		}
	}
	public static void Load(Harmony harmony)
	{
		//IL_0008: Expected O, but got Unknown
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Expected O, but got Unknown
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Expected O, but got Unknown
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Expected O, but got Unknown
		//IL_0131: Expected O, but got Unknown
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Expected O, but got Unknown
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Expected O, but got Unknown
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Expected O, but got Unknown
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Expected O, but got Unknown
		bool flag = default(bool);
		try
		{
			PreloadAssemblies();
		}
		catch (FileNotFoundException val)
		{
			FileNotFoundException val2 = val;
			ManualLogSource? log = Plugin.Log;
			BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(103, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Could not find a required MonkeyLoader file!\nThis means MonkeyLoader will not be loaded!\nMissing file: ");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(val2.FileName);
			}
			log.LogError(val3);
			return;
		}
		catch (global::System.Exception)
		{
			ManualLogSource? log2 = Plugin.Log;
			BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(42, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error occurred when preloading assemblies.");
			}
			log2.LogError(val3);
			throw;
		}
		try
		{
			global::System.Type declaringType = ((MemberInfo)_monkeyLoaderWrapperAsm.EntryPoint).DeclaringType;
			_resolveNativeLibraryMethod = AccessTools.Method(declaringType, "ResolveNativeLibrary", (global::System.Type[])null, (global::System.Type[])null);
			MethodInfo val4 = Enumerable.FirstOrDefault<MethodInfo>((global::System.Collections.Generic.IEnumerable<MethodInfo>)AccessTools.GetDeclaredMethods(declaringType), (Func<MethodInfo, bool>)((MethodInfo m) => m.ReturnType == typeof(global::System.Threading.Tasks.Task) && ((MemberInfo)m).Name == "Main"));
			harmony.Patch((MethodBase)(object)AccessTools.AsyncMoveNext((MethodBase)(object)val4), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod((global::System.Delegate)(object)new Func<global::System.Collections.Generic.IEnumerable<CodeInstruction>, global::System.Collections.Generic.IEnumerable<CodeInstruction>>(MonkeyLoaderWrapperPatch.Transpiler)), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.PatchAll();
		}
		catch (global::System.Exception)
		{
			ManualLogSource? log3 = Plugin.Log;
			BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(29, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error occurred when patching.");
			}
			log3.LogError(val3);
			throw;
		}
		try
		{
			((MethodBase)_monkeyLoaderWrapperAsm.EntryPoint).Invoke((object)null, new object[1]);
		}
		catch (TargetInvocationException val5)
		{
			if (!(((global::System.Exception)val5).InnerException is MonkeyLoaderWrapperPatch.ExplodeException))
			{
				ManualLogSource? log4 = Plugin.Log;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(36, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error occurred in MonkeyLoader code.");
				}
				log4.LogError(val3);
				throw;
			}
		}
		catch (global::System.Exception)
		{
			ManualLogSource? log5 = Plugin.Log;
			BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(36, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error occurred in MonkeyLoader code.");
			}
			log5.LogError(val3);
			throw;
		}
		DllImportResolver val6 = (DllImportResolver)global::System.Delegate.CreateDelegate(typeof(DllImportResolver), _resolveNativeLibraryMethod);
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		for (int i = 0; i < assemblies.Length; i++)
		{
			NativeLibrary.SetDllImportResolver(assemblies[i], val6);
		}
		Plugin.Log.LogInfo((object)"Done!");
	}
}
[ResonitePlugin("Nytra.MonkeyLoaderLoader", "MonkeyLoaderLoader", "1.0.0", "Nytra", "https://github.com/Nytra/MonkeyLoaderLoader-BepInEx")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BasePlugin
{
	internal static ManualLogSource? Log;
	public override void Load()
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		Log = ((BasePlugin)this).Log;
		ManualLogSource? log = Log;
		bool flag = default(bool);
		BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(21, 0, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Loading MonkeyLoader!");
		}
		log.LogInfo(val);
		MonkeyLoaderLoader.Load(((BasePlugin)this).HarmonyInstance);
	}
}
public static class PluginMetadata
{
	public const string GUID = "Nytra.MonkeyLoaderLoader";
	public const string NAME = "MonkeyLoaderLoader";
	public const string VERSION = "1.0.0";
	public const string AUTHORS = "Nytra";
	public const string REPOSITORY_URL = "https://github.com/Nytra/MonkeyLoaderLoader-BepInEx";
}