using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace PkmnLibSharp.Utilities
{
    internal static class MarshalHelper
    {
        internal static IntPtr ToPtr(this string? s)
        {
            if (s == null) return IntPtr.Zero;
            return Marshal.StringToHGlobalAnsi(s);
        }

        internal static string? PtrString(this IntPtr i)
        {
            return i == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(i);
        }
        
        internal static IntPtr ArrayPtr(this IntPtr[] a)
        {
            return Marshal.UnsafeAddrOfPinnedArrayElement(a, 0);
        }
        internal static IntPtr ArrayPtr<T>(this T[] a) where T : struct, IConvertible
        {
            return Marshal.UnsafeAddrOfPinnedArrayElement(a, 0);
        }
        
        internal static IntPtr ArrayPtr(this PointerWrapper?[] a)
        {
            return Marshal.UnsafeAddrOfPinnedArrayElement(a.Select(x => x?.Ptr ?? IntPtr.Zero).ToArray(), 0);
        }



        internal const byte True = 1;
        internal const byte False = 0;

        internal static byte ToNative(this bool b)
        {
            return b ? True : False;
        }
    }
}