using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

/// <summary>
/// SDK 可供外部调用的一些工具方法
/// </summary>
public static class ToukaUtils
{

    /// <summary>
    /// 跳转隐私链接
    /// </summary>
    public static void OpenPrivacyURL() 
    {
        Application.OpenURL("http://www.toukagame.com/PrivacyPolicy.html");
    }

    public static void OpenUserPolicy()
    {
        Application.OpenURL("https://www.toukagame.com/agreement.html");
    }

    /// <summary>
    /// 打开更多游戏 - 跳转appstore公司账号页面
    /// </summary>
    /// <param name="_withRedPotActive"></param>
    public static void OpenMoreGames()
    {
#if UNITY_IOS
        Application.OpenURL("https://apps.apple.com/cn/developer/toukagames/id1544391713");
#endif
    }

    /// <summary>
    /// 打开URL
    /// </summary>
    /// <param name="_url"></param>
    public static void OpenUrl(string _url)
    {
        Application.OpenURL(_url);
    }

    /// <summary>
    /// 一键加入QQ群
    /// </summary>
    public static void JoinQQGroup()
    {
        string qqUrl = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=916827975&key=ed38055c01233796a17ff0a800c9967cdf1c2b82dfc98d287130dfe1324b411d&card_type=group&source=external&jump_from=webapi";
        Application.OpenURL(qqUrl);
    }

    /// <summary>
    /// 打开评价链接 - 跳转游戏商店页
    /// </summary>
    public static void OpenReviewURL()
    {
#if UNITY_ANDROID
        Debug.Log("Review url = " + StaticStringsKey.REVIEW_URL + Application.identifier);
        Application.OpenURL(StaticStringsKey.REVIEW_URL+Application.identifier);
        return;
#endif
        Application.OpenURL(StaticStringsKey.REVIEW_URL);
    }

    /// <summary>
    /// iOS游戏内弹出系统评价窗口
    /// </summary>
    public static void OpenSystemReviewPop()
    {
        Debug.Log("游戏内跳出评价");
#if UNITY_IOS
        TGTools.Instance.ShowReview();
#endif
    }

    /// <summary>
    /// 需要延迟初始化tenjin时调用
    /// </summary>
    public static void InitTenjinFirst()
    {
        ToukaAnalyticsManager.Instance.InitTenjinInner();
        SavePlayerPrefsIntByKeyValue(StaticStringsPlayerPrefs.HasInitTenjinFirst, 1);
    }

    /// <summary>
    /// 是否首次触达某个事件
    /// </summary>
    /// <param name="_key"></param>
    /// <returns></returns>
    public static bool IfFirstCheckPlayerPrefs (string _key) {
        var isFirstClick = GetPlayerPrefsIntByKey(_key) == 0;
        SavePlayerPrefsIntByKeyValue(_key, 1);

        return isFirstClick;
    }

    /// <summary>
    /// 只首次触发某个事件进行打点
    /// </summary>
    /// <param name="_logType"></param>
    /// <param name="_eventKey"></param>
    /// <param name="_eventLabel"></param>
    public static void LogFirstEvent (ToukaLogType _logType, string _eventKey) {
        var isFirstClick = IfFirstCheckPlayerPrefs (_eventKey);
        if (isFirstClick) {
            ToukaAnalyticsManager.Instance.LogEvent(_logType, _eventKey);
        }
    }

    /// <summary>
    /// 是否是中文
    /// </summary>
    public static bool IsCN {
        get
        {
            var language = Application.systemLanguage.ToString().ToLower();
            if (language.Contains("chinese"))
            {
                return true;
            }
            return false;
        }
    }

    /// <summary>
    /// 本地存int
    ///
    /// key 内部拼接了前缀：Touka_
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_defaultValue"></param>
    /// <returns></returns>
    public static int GetPlayerPrefsIntByKey(string _key, int _defaultValue = 0)
    {
        int value = PlayerPrefs.GetInt(string.Format("{0}{1}", StaticStringsPlayerPrefs.TOUKA_PREFIX, _key), _defaultValue);
        return value;
    }

    /// <summary>
    /// 本地取int
    ///
    /// key 内部拼接了前缀：Touka_
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_newValue"></param>
    public static void SavePlayerPrefsIntByKeyValue(string _key, int _newValue)
    {
        PlayerPrefs.SetInt(string.Format("{0}{1}", StaticStringsPlayerPrefs.TOUKA_PREFIX, _key), _newValue);
        PlayerPrefs.Save();
    }

    /// <summary>
    /// 本地存string
    ///
    /// key 内部拼接了前缀：Touka_
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_defaultValue"></param>
    /// <returns></returns>
    public static string GetPlayerPrefsStringByKey(string _key, string _defaultValue = "")
    {
        string value = PlayerPrefs.GetString(string.Format("{0}{1}", StaticStringsPlayerPrefs.TOUKA_PREFIX, _key), _defaultValue);
        return value;
    }

    /// <summary>
    /// 本地取string
    ///
    /// key 内部拼接了前缀：Touka_
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_newValue"></param>
    public static void SavePlayerPrefsStringByKeyValue(string _key, string _newValue)
    {
        PlayerPrefs.SetString(string.Format("{0}{1}", StaticStringsPlayerPrefs.TOUKA_PREFIX, _key), _newValue);
        PlayerPrefs.Save();
    }


    /// <summary>
    /// 缓存当前时间
    /// </summary>
    /// <param name="_key"></param>
    public static void SaveCurrTime2PlayerPrefs(string _key)
    {
        DateTime date1 = DateTime.Now;
        string s1 = date1.ToString();
        SavePlayerPrefsStringByKeyValue(_key, s1);
    }

    /// <summary>
    /// 缓存本地时间为string
    /// </summary>
    /// <param name="_key"></param>
    /// <param name="_dateStr"></param>
    public static void SaveCurrTime2PlayerPrefsWithStringDate(string _key, string _dateStr)
    {
        SavePlayerPrefsStringByKeyValue(_key, _dateStr);
    }

    /// <summary>
    /// 取出缓存string时间为 DateTime
    /// </summary>
    /// <param name="_key"></param>
    /// <returns></returns>
    public static DateTime GetDateTimeFromPlayerPrefs(string _key)
    {
        string firstDateValue = GetPlayerPrefsStringByKey(_key);
        if (string.IsNullOrEmpty(firstDateValue))
        {
            return new DateTime(1990, 1, 1, 0, 0, 0);
        }
        DateTime dateOld = Convert.ToDateTime(firstDateValue);
        return dateOld;
    }

    /// <summary>
    /// 判断是否为新用户
    ///
    /// 距离首次登录时间间隔24h以内为新用户
    /// </summary>
    /// <returns></returns>
    public static bool isNewUser()
    {
        DateTime dateCurr = DateTime.Now;

        string firstDateValue = GetPlayerPrefsStringByKey(StaticStringsPlayerPrefs.FirstLoginTime);
        if (string.IsNullOrEmpty(firstDateValue))
        {
            Debug.Log("存的值为空，为新用户");
            return true;
        }
        Debug.Log("读取出来的值： " + firstDateValue + " ， 现在的时间值：" + dateCurr.ToString());     // 06/16/2019 19:46:57
        DateTime dateOld = Convert.ToDateTime(firstDateValue);

        TimeSpan timeSpan = dateCurr - dateOld;
        Debug.Log("timeSpan.Seconds : " + timeSpan.TotalMinutes);
        if(timeSpan.TotalMinutes >= 24 * 60)
        {
            Debug.Log("不是新用户了");
            return false;
        }
        Debug.Log("是新用户");
        return true;
    }

    /// <summary>
    /// equal double
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    public static bool equalDouble(double a, double b)
    {
        if ((a - b > -0.000001) && (a - b) < 0.000001)
            return true;
        else
            return false;
    }

    /// <summary>
    /// Floats the equal.
    /// </summary>
    /// <returns><c>true</c>, if equal was floated, <c>false</c> otherwise.</returns>
    /// <param name="a">The alpha component.</param>
    /// <param name="b">The blue component.</param>
    public static bool FloatEqual(float a, float b)
    {
        if ((a - b > -0.000001) && (a - b) < 0.000001)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static string GetTodayDataStr()
    {
        string timeStr = DateTime.Now.ToString("yyyy-MM-dd");
        return timeStr;
    }

    public static void CheckPassLvAndAdEvent(int pLvNum, bool pWithAdCheck = false)
    {
        //Debug.Log("is first day ==: " + ToukaUtilsInner.Instance.isFirstDayLogin);
        //Debug.Log("pass lv count ==: " + pLvNum);
        if (ToukaUtilsInner.Instance.isFirstDayLogin && pLvNum >= int.Parse(StaticOnlineParams.NewUserPassXLevelOnlineParams.DefaultValue))
        {
            string tPassLvKey = "PassLv_Log";
            if (IfFirstCheckPlayerPrefs(tPassLvKey))
            {
                ToukaAnalyticsManager.Instance.LogEvent(ToukaLogType.Tenjin, StaticStringsEvent.Event_Tenjin_TKInner_NewUserPassLevelX);
                ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Tenjin_TKInner_NewUserPassLevelX);
            }

            if (pWithAdCheck)
            {
                CheckAdCount();
            }
        }
    }

    private static void CheckAdCount()
    {
        var videoCount = GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.VideoShowCount);
        var intersitialCount = GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.IntersitialShowCount);
        string tLvAndAdKey = "PassLv&AdCount_Log";
        string tEvtPassLvAndAdCount = "Passlevel&Count_Video";

        //Debug.Log("watch ad count ==: " + (videoCount + intersitialCount));
        if ((videoCount + intersitialCount) >= int.Parse(StaticOnlineParams.NewUserAdsCountOnlineParams.DefaultValue))
        {
            if (IfFirstCheckPlayerPrefs(tLvAndAdKey))
            {
                ToukaAnalyticsManager.Instance.LogEvent(ToukaLogType.Tenjin, tEvtPassLvAndAdCount);
                ToukaSDKManager.Instance.LogEventByUmeng(tEvtPassLvAndAdCount);
            }
        }
    }
}