using System.Collections.Generic;

using GameAnalyticsSDK;
using GameAnalyticsSDK.Events;
using UnityEngine;

using GameAnalyticsSDK.Wrapper;
using Touka.GameLogic;

/// <summary>
/// 数据统计类
///
/// 包含Umeng、GA、Tenjin的初始化及打点；Umeng在线参数初始化；
/// ** 需在 StaticStringKey 类里修改对应ID
/// </summary>
public class ToukaAnalyticsManager : ToukaSingletonMonoBehaviour<ToukaAnalyticsManager>
{
    /// <summary>
    /// Init
    /// </summary>
    public void Init()
    {
        Debug.Log("[ToukaAnalyticsManager] Init");

#if UNITY_EDITOR
        return;
#endif
        StaticOnlineParams.Instance.InitData();     // 初始化在线参数列表
        
        InitUmeng();        // 初始化umeng
        InitGA();           // 初始化ga
        InitTenjin();       // 初始化tenjin

        StaticOnlineParams.GetInstance().Init();        // 初始化在线参数

        ToukaUtilsInner.Instance.Check2DaysLogin();     // 检查次日登录
        ToukaUtilsInner.Instance.SaveFirstLoginTime();      // 记录首次登录游戏时间
    }

#region Inits

    /// <summary>
    /// 初始化Umeng
    /// </summary>
    private void InitUmeng()
    {
#if UNITY_IOS
        TGTools.Instance.onRemoteConfigHandler = GetRemoteConfigOnline;
        TGTools.Instance.InitSdk(StaticStringsKey.UMENG_APPKEY, StaticStringsKey.UMENG_CHANNELID);
        Umeng.Analytics.SetLogEnabled(true);
#elif UNITY_ANDROID
        Umeng.Analytics.StartWithAppKeyAndChannelId (StaticStringsKey.UMENG_APPKEY, StaticStringsKey.UMENG_CHANNELID);
        Umeng.Analytics.SetLogEnabled (false);
#endif
    }

    /// <summary>
    /// Umeng在线参数回调
    /// </summary>
    public void GetRemoteConfigOnline()
    {
        Debug.Log("[ToukaAnalyticsManager] get remote config from online");

        StaticOnlineParams.Instance.parseGameOnlineConfig();
    }

    /// <summary>
    /// 初始化GA
    /// </summary>
    private void InitGA()
    {
        if (UnityEngine.Object.FindObjectOfType(typeof(GameAnalytics)) == null)
        {
            GameObject ga = new GameObject();
            ga.name = "GameAnalytics";
            ga.transform.parent = transform;
            ga.AddComponent<GA_SpecialEvents>();
            ga.AddComponent<GameAnalytics>();
        }
        else
        {
            Debug.LogWarning("A GameAnalytics object already exists in this scene - you should never have more than one per scene!");
        }

        GameAnalytics.Initialize();
        GA_Wrapper.SetBuild(Application.version);
        GA_Wrapper.Initialize(StaticStringsKey.GA_gameKey, StaticStringsKey.GA_secretKey);

        Debug.Log("[ToukaAnalyticsManager] GA: init :GA_gameKey=" + StaticStringsKey.GA_gameKey + "GA_secretKey=" + StaticStringsKey.GA_secretKey + " Application.version=" + Application.version);
    }

    /// <summary>
    /// 初始化Tenjin
    /// </summary>
    private void InitTenjin()
    {
#if IOS_CN
        if (!StaticOtherConfig.InitTenjinLater_Switch)      // 启动就初始化tenjin
        {
            InitTenjinInner();
        }
        else        // 延时初始化tenjin
        {
            if (ToukaUtils.GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.HasInitTenjinFirst, 0) == 1)
            {
                Debug.Log("首次初始化过tenjin了，之后都可以正常初始了");
                InitTenjinInner();
            }
            else
            {
                Debug.Log("需要延迟，启动处不能初始化tenjin");
            }
        }
#else
        InitTenjinInner();
#endif
    }

    /// <summary>
    /// 实际调用初始化Tenjin
    /// </summary>
    public void InitTenjinInner()
    {
        Debug.Log("[ToukaAnalyticsManager] init tenjin inner");
        BaseTenjin instance = Tenjin.getInstance(StaticStringsKey.TENJIN_KEY);

        // Sends install/open event to Tenjin
        instance.Connect();
    }

#endregion

#region Events

    /// <summary>
    /// 打点事件 Tenjin / GA
    /// </summary>
    /// <param name="_logType"> Tenjin / GA </param>
    /// <param name="_eventName"> 事件名称 </param>
    /// <param name="_label"> 事件属性（可选） </param>
	public void LogEvent (ToukaLogType _logType, string _eventName, string _label = null) {
		Debug.Log ("[ToukaAnalyticsManager] LogEvent, logType : " + _logType.ToString() +  " , eventName " + _eventName + " label:" + _label);

#if UNITY_EDITOR
		return;
#endif
		if (string.IsNullOrEmpty (_eventName)) return;

        // ga
        if ((_logType & ToukaLogType.GA) > 0)
        {
            if (string.IsNullOrEmpty(_label))
            {
                GameAnalytics.NewDesignEvent("event:" + _eventName);
            }
            else
            {
                GameAnalytics.NewDesignEvent("event:" + _eventName + "_" + _label);
            }
        }

        // tenjin
        if ((_logType & ToukaLogType.Tenjin) > 0)
        {
            if (string.IsNullOrEmpty(_label))
            {
                Tenjin.getInstance(StaticStringsKey.TENJIN_KEY).SendEvent(_eventName);
            }
            else
            {
                Tenjin.getInstance(StaticStringsKey.TENJIN_KEY).SendEvent(_eventName + _label);
            }
            Debug.Log("Touka LogEventWithLabel Tenjin: " + _eventName + " label:" + _label);
        }
    }

    /// <summary>
    /// umeng打点 - 事件名字
    /// </summary>
    /// <param name="_eventSort">事件名字</param>
    public void LogEventByUmeng(string _eventSort)
    {
#if !NO_SDK
        Debug.Log("Touka LogEventByUmeng _eventSort : " + _eventSort);

#if UNITY_EDITOR
        return;
#endif
        Umeng.Analytics.Event(_eventSort);
#endif
    }

    /// <summary>
    /// umeng 打点 - 事件名字 + 一个事件属性(key:value)
    /// </summary>
    /// <param name="_eventSort">事件名字</param>
    /// <param name="_key">属性key</param>
    /// <param name="_value">属性value</param>
    public void LogEventByUmeng(string _eventSort, string _key, string _value)
    {
        if(!string.IsNullOrEmpty(_eventSort) && !string.IsNullOrEmpty(_key) && !string.IsNullOrEmpty(_value))
        {
            LogEventByUmeng(_eventSort, new Dictionary<string, string>() { { _key, _value} });
        }
    }

    /// <summary>
    /// umeng 打点 - 事件名字 + 两个事件属性(key:value)
    /// </summary>
    /// <param name="_eventSort">事件名字</param>
    /// <param name="_key01"> 属性1-key </param>
    /// <param name="_value01"> 属性1-value </param>
    /// <param name="_key02"> 属性2-key  </param>
    /// <param name="_value02"> 属性2-value </param>
    public void LogEventByUmeng(string _eventSort, string _key01, string _value01, string _key02, string _value02)
    {
        if (!string.IsNullOrEmpty(_eventSort) && !string.IsNullOrEmpty(_key01) && !string.IsNullOrEmpty(_value01) && !string.IsNullOrEmpty(_key02) && !string.IsNullOrEmpty(_value02))
        {
            LogEventByUmeng(_eventSort, new Dictionary<string, string>() { { _key01, _value01 }, {_key02, _value02 } });
        }
    }

    /// <summary>
    /// umeng 打点 - 事件名字 + 事件属性字典
    /// </summary>
    /// <param name="_eventSort"> 事件名字 </param>
    /// <param name="_eventDic"> 事件属性字典 </param>
    public void LogEventByUmeng(string _eventSort, Dictionary<string, string> _eventDic = null)
    {
        string eventStr = "UMENG LOG _eventSort : " + _eventSort + " -> ";

        if(_eventDic != null)
        {
            foreach (var kvp in _eventDic)
            {
                eventStr += string.Format(" (Key = {0}, Value = {1} ) , ", kvp.Key, kvp.Value);
            }
        }

        Debug.Log(eventStr);
#if !NO_SDK
#if UNITY_EDITOR
        return;
#endif
        if (!string.IsNullOrEmpty(_eventSort))
        {
            if(_eventDic != null && _eventDic.Count == 0)
            {
                Umeng.Analytics.Event(_eventSort);
            }
            else if(_eventDic != null && _eventDic.Count > 0)
            {
                Umeng.Analytics.Event(_eventSort, _eventDic);
            }else if(_eventDic == null)
            {
                Umeng.Analytics.Event(_eventSort);
            }
        }
        else
        {
            Debug.LogError("UMENG Event Sort is Empty!");
        }
#endif
    }

    /// <summary>
    /// Umeng 打点广告按钮展示
    /// </summary>
    /// <param name="_adShow"></param>
    public void LogEventByUmengAdShow(string _adShow)
    {
        if (!string.IsNullOrEmpty(_adShow))
        {
            ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_ad_button_show, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _adShow } });
        }
    }

#endregion
}

public enum ToukaLogType {
	GA = 1,
    Tenjin = 1 << 6,
}
