using System;
using System.Runtime.InteropServices;
using Decal.Adapter.Support;
using Decal.Interop.Core;
using Microsoft.Win32;

namespace Decal.Adapter;

[ComVisible(true)]
[ComDefaultInterface(typeof(IDecalService))]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("DecalAdapter.Lifetime")]
[Guid("71A69713-6593-47EC-0001-0000000DECA1")]
public sealed class LifetimeProxy : MarshalByRefObject, IDecalService, IDecalDirectory, IDecalWindowsMessageSink
{
	private CoreManager myLifetime;

	public LifetimeProxy()
	{
		Util.WriteLine("Lifetime Proxy retrieving Lifetime manager");
		myLifetime = CoreManager.Current;
		Util.WriteLine("Lifetime Proxy ctor complete");
	}

	[ComRegisterFunction]
	internal static void SelfRegister(Type t)
	{
		RegistryKey registryKey = Registry.LocalMachine.CreateSubKey("Software\\Decal\\Services").CreateSubKey("{71A69713-6593-47EC-0001-0000000DECA1}");
		registryKey.SetValue("", "Decal .NET Lifetime Service", RegistryValueKind.String);
		registryKey.SetValue("Enabled", true, RegistryValueKind.DWord);
		RegistryKey registryKey2 = Registry.LocalMachine.CreateSubKey("Software\\Decal\\Surrogates").CreateSubKey("{71A69713-6593-47EC-0002-0000000DECA1}");
		registryKey2.SetValue("", "Decal.Adapter Surrogate", RegistryValueKind.String);
		registryKey2.SetValue("Enabled", true, RegistryValueKind.DWord);
	}

	[ComUnregisterFunction]
	internal static void UnRegister(Type t)
	{
	}

	void IDecalService.AfterPlugins()
	{
	}

	void IDecalService.BeforePlugins()
	{
	}

	void IDecalService.Initialize(DecalCore pDecal)
	{
		if (!RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
		{
			Util.WriteLine("Can't load v2 mixed-mode");
		}
		myLifetime.Initialize(pDecal);
	}

	void IDecalService.Terminate()
	{
		myLifetime.Terminate();
	}

	object IDecalDirectory.Lookup(string strName)
	{
		return null;
	}

	bool IDecalWindowsMessageSink.WindowMessage(int HWND, short uMsg, int wParam, int lParam)
	{
		return myLifetime.FireWindowMessage(HWND, uMsg, wParam, lParam);
	}
}
