using System.Collections.Generic;
using Newtonsoft.Json;
using ThinkingData.Analytics;
using Combo.Platform;

namespace Combo.Core
{
    public static class ThinkingDataManager
    {
        [System.Serializable]
        internal class Parameters
        {
            [JsonProperty("thinking_data_app_id")]
            public string appId;
            [JsonProperty("thinking_data_receiver_url")]
            public string serverUrl;
        }

        internal static void Setup()
        {
            var paramz = Native.GetParameters<Parameters>();

            if (string.IsNullOrEmpty(paramz.appId) || string.IsNullOrEmpty(paramz.serverUrl))
            {
                Log.W($"Initialization of ThinkingDataAnalytics aborted, received empty parameters");
                return;
            }
            TDAnalytics.Init(paramz.appId, paramz.serverUrl);
            TDAnalytics.SetDistinctId(Native.GetDeviceId(), paramz.appId);
            SetSuperProperties(
                GetSuperProperties()
            );
            Log.I($"ThinkingDataAnalytics initialized");
        }

        internal static void SetSuperProperties(Dictionary<string, object> properties)
        {
            if(properties == null)
            {
                return;
            }
            Dictionary<string, object> validProperties = new Dictionary<string, object>();

            foreach (var property in properties)
            {
                if (!string.IsNullOrEmpty(property.Value?.ToString()))
                {
                    validProperties[property.Key] = property.Value;
                }
                else
                {
                    TDAnalytics.UnsetSuperProperty(property.Key);
                }
            }

            TDAnalytics.SetSuperProperties(validProperties);
        }

        internal static Dictionary<string,object> GetSuperProperties() {
            var superProperties = new Dictionary<string, object>
            {
                { "distro", Native.GetDistro() },
                { "variant", Native.GetVariant() }
            };

            return superProperties;
        }

        internal static void PutExtraWithDistinctId(Dictionary<string, object> extra)
        {
            extra["thinking_data_distinct_id"] = TDAnalytics.GetDistinctId();
        }
    }
}
