namespace Stove.StoveSDK
{
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using MiniJSON;

    /**
     * GameLog provided by the Stove.
     *
     * From 3.0.0 the game log runs as an independent module (StoveGameLog) with no
     * dependency on other SDK modules. Call Configure once at startup, then use Add/Flush.
     * @since 3.0.0
     */
    public class GameLog
    {
        // Kept alive for the app lifetime so the native module can invoke it lazily
        // at every log-creation time. Invoked from a native background thread, so the
        // resolver body provided by the game must be thread-safe.
        private static Func<GameLogUserInfo> _userInfoResolver;

        /**
         * Configures the game log module. Call once at startup (e.g. right after SDK initialize).
         *
         * All values are injected by the game/CP. The module has no dependency on other SDK
         * modules, so partner settings, GDS and user information are all provided here.
         *
         * @param serverUrl Full log collector URL including the game id.
         * @param serviceId Game id. Used as the log's app_id field.
         * @param marketGameId market_game_id registered in the market settings.
         * @param environment Build environment: "sandbox" or "live".
         * @param batchSize Send batch size (1~50). 0 disables the feature. (Clamped to 1~50.)
         * @param ip Client IP. Used as the log's client_ip field.
         * @param gds Access info (GDS). Sent as gds_info; country uses this map's "nation" value.
         * @param language SDK language value. Used as the log's locale field.
         * @param externalId External identifier. Sent as id_engine.external_id (optional).
         * @param userInfoResolver Function returning the latest GameLogUserInfo. Called lazily
         *        at every log-creation time so the newest user info is always used.
         * @since 3.0.0
         */
        public static void Configure(
            string serverUrl,
            string serviceId,
            string marketGameId,
            string environment,
            int batchSize,
            string ip,
            Dictionary<string, object> gds,
            string language,
            string externalId,
            Func<GameLogUserInfo> userInfoResolver)
        {
            Debug.Log("GameLog.Configure");

            _userInfoResolver = userInfoResolver;

            string gdsJson = Json.Serialize(gds ?? new Dictionary<string, object>());

            try
            {
                GameLogInterface.Configure(
                    serverUrl,
                    serviceId,
                    marketGameId,
                    environment,
                    batchSize,
                    ip ?? string.Empty,
                    gdsJson,
                    language,
                    externalId);
            }
            catch (Exception e)
            {
                Debug.LogError("GameLog.Configure failed: " + e.Message);
            }
        }

        /**
         * Send events to the stove game log collector.
         *
         * Please use after GameLog.Configure.
         * @param logEvent GameLog's Event containing parameters and additionalParameters.
         * @param action Callback for add result.
         * @see GameLogResult
         * @since 3.0.0
         */
        public static void Add(GameLogEvent logEvent, Action<GameLogResult> action)
        {
            Debug.Log("GameLog.Add");

            if (logEvent == null)
            {
                Debug.LogError("GameLog.Add failed: logEvent is null");
                action?.Invoke(GameLogResult.Cancel());
                return;
            }

            bool hasParameters = logEvent.Parameters != null && logEvent.Parameters.Count > 0;
            if (!hasParameters)
            {
                Debug.LogError("GameLog.Add failed: GameLogEvent.Parameters is required");
                action?.Invoke(GameLogResult.Cancel());
                return;
            }

            try
            {
                string jsonString = logEvent.ToJSONString();

                string identifier = StoveSDK.Instance.AddAction(payload =>
                {
                    try
                    {
                        var resultDictionary = payload["result"] as Dictionary<string, object>;
                        GameLogResult result = new GameLogResult(resultDictionary);

                        Debug.Log("GameLog.Add Result : " + result);

                        action?.Invoke(result);
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("GameLog.Add callback failed: " + e.Message);
                        action?.Invoke(GameLogResult.Cancel());
                    }
                });

                GameLogInterface.Add(jsonString, identifier);
            }
            catch (Exception e)
            {
                Debug.LogError("GameLog.Add failed: " + e.Message);
                action?.Invoke(GameLogResult.Cancel());
            }
        }

        /**
         * Sends all pending game logs immediately.
         * @since 3.0.0
         */
        public static void Flush()
        {
            try
            {
                Debug.Log("GameLog.Flush");
                GameLogInterface.Flush();
            }
            catch (Exception e)
            {
                Debug.LogError("GameLog.Flush failed: " + e.Message);
            }
        }

        /**
         * Resolves the current user info as a JSON string for the native module.
         * Invoked by the platform interface layer from a native thread.
         * @return JSON with "userId"/"characterNo"/"worldId", or null when unavailable.
         * @since 3.0.0
         */
        internal static string ResolveUserInfoJson()
        {
            Func<GameLogUserInfo> resolver = _userInfoResolver;
            if (resolver == null)
            {
                return null;
            }

            try
            {
                GameLogUserInfo info = resolver.Invoke();
                if (info == null)
                {
                    return null;
                }
                return Json.Serialize(info.ToDictionary());
            }
            catch (Exception e)
            {
                Debug.LogError("GameLog.ResolveUserInfoJson failed: " + e.Message);
                return null;
            }
        }
    }
}
