using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Dalamud.Game;
using Dalamud.Interface;
using ImGuiNET;

namespace MultiboxMutexer;

internal static class Util
{
	internal static bool TryScanText(this SigScanner scanner, string sig, out nint result)
	{
		result = IntPtr.Zero;
		try
		{
			result = scanner.ScanText(sig);
			return true;
		}
		catch (KeyNotFoundException)
		{
			return false;
		}
	}

	private unsafe static byte[] ReadTerminatedBytes(byte* ptr)
	{
		if (ptr == null)
		{
			return new byte[0];
		}
		List<byte> list = new List<byte>();
		while (*ptr != 0)
		{
			list.Add(*ptr);
			ptr++;
		}
		return list.ToArray();
	}

	internal unsafe static string ReadTerminatedString(byte* ptr)
	{
		return Encoding.UTF8.GetString(ReadTerminatedBytes(ptr));
	}

	internal static bool ContainsIgnoreCase(this string haystack, string needle)
	{
		return CultureInfo.InvariantCulture.CompareInfo.IndexOf(haystack, needle, CompareOptions.IgnoreCase) >= 0;
	}

	internal static bool IconButton(FontAwesomeIcon icon, string id)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		ImGui.PushFont(UiBuilder.IconFont);
		bool result = ImGui.Button(FontAwesomeExtensions.ToIconString(icon) + "##" + id);
		ImGui.PopFont();
		return result;
	}
}
