#if UNITY_IOS

namespace Stove.StoveSDK
{
    using System;
    using System.Runtime.InteropServices;
    using AOT;

    public class GameLogInterface
    {
        // Native user-info resolver callback.
        // Returns a pointer to a UTF-8 C string owned by C#, valid until the next call.
        // The native module invokes it lazily at every log-creation time (on a background
        // thread) so the newest user info is always used.
        delegate IntPtr UserInfoResolverDelegate();

        // Kept alive for the app lifetime so the native function pointer stays valid.
        static readonly UserInfoResolverDelegate resolverDelegate = ResolveUserInfo;

        static IntPtr lastUserInfoPtr = IntPtr.Zero;

        [MonoPInvokeCallback(typeof(UserInfoResolverDelegate))]
        static IntPtr ResolveUserInfo()
        {
            // Free the previously handed-out buffer before allocating a new one.
            if (lastUserInfoPtr != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(lastUserInfoPtr);
                lastUserInfoPtr = IntPtr.Zero;
            }

            string json = GameLog.ResolveUserInfoJson();
            if (json == null)
            {
                return IntPtr.Zero;
            }

            lastUserInfoPtr = Marshal.StringToHGlobalAnsi(json);
            return lastUserInfoPtr;
        }

        [DllImport("__Internal")]
        private static extern void stove_game_log_configure(
            string serverUrl,
            string serviceId,
            string marketGameId,
            string environment,
            int batchSize,
            string ip,
            string gdsJson,
            string language,
            string externalId,
            UserInfoResolverDelegate userInfoResolver);

        internal static void Configure(
            string serverUrl,
            string serviceId,
            string marketGameId,
            string environment,
            int batchSize,
            string ip,
            string gdsJson,
            string language,
            string externalId)
        {
            stove_game_log_configure(
                serverUrl,
                serviceId,
                marketGameId,
                environment,
                batchSize,
                ip,
                gdsJson,
                language,
                externalId,
                resolverDelegate);
        }

        [DllImport("__Internal")]
        private static extern void stove_game_log_add(string logEvent, string identifier);
        internal static void Add(string logEvent, string identifier)
        {
            stove_game_log_add(logEvent, identifier);
        }

        [DllImport("__Internal")]
        private static extern void stove_game_log_flush();
        internal static void Flush()
        {
            stove_game_log_flush();
        }
    }
}

#endif
