using System;
using System.Runtime.InteropServices;
using FFXIVClientStructs.FFXIV.Client.System.Framework;

namespace OmicronMountMusicFixer;

public static class BGMAddressResolver
{
	private static nint _baseAddress;

	private static nint _musicManager;

	public static nint AddRestartId { get; private set; }

	public static nint GetSpecialMode { get; private set; }

	public static nint BGMSceneManager => Marshal.ReadIntPtr(_baseAddress);

	public static nint BGMSceneList
	{
		get
		{
			nint num = Marshal.ReadIntPtr(_baseAddress);
			if (num != IntPtr.Zero)
			{
				return Marshal.ReadIntPtr(num + 192);
			}
			return IntPtr.Zero;
		}
	}

	public static bool StreamingEnabled => Marshal.ReadByte(_musicManager + 50) == 1;

	public unsafe static void Init()
	{
		_baseAddress = DalamudApi.SigScanner.GetStaticAddressFromSig("48 8B 05 ?? ?? ?? ?? 48 85 C0 74 51 83 78 08 0B", 0);
		AddRestartId = DalamudApi.SigScanner.ScanText("E8 ?? ?? ?? ?? 88 9E ?? ?? ?? ?? 84 DB");
		GetSpecialMode = DalamudApi.SigScanner.ScanText("40 57 48 83 EC 20 48 83 79 ?? ?? 48 8B F9 0F 84 ?? ?? ?? ?? 0F B6 51 4D");
		DalamudApi.PluginLog.Debug($"[BGMAddressResolver] init: base address at {((IntPtr)_baseAddress).ToInt64():X}", Array.Empty<object>());
		int num = Marshal.ReadInt32((nint)DalamudApi.SigScanner.ScanText("48 8B 8F ?? ?? ?? ?? 85 C0 0F 95 C2 E8 ?? ?? ?? ?? 48 8B 9F") + 3);
		_musicManager = Marshal.ReadIntPtr(new IntPtr(Framework.Instance()) + num);
		DalamudApi.PluginLog.Debug($"[BGMAddressResolver] MusicManager found at {((IntPtr)_musicManager).ToInt64():X}", Array.Empty<object>());
	}
}
