using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
namespace EFSDK
{
    /// 
    /// TKG Native SDK Android platform interface call
    /// 
    public class EFSdk
    {
        private static EFSdk _mEfSdk;
        // 保持变量名不变
        private static string mappingInfo = "";
        public static EFSdk get()
        {
            if (_mEfSdk == null)
            {
                _mEfSdk = new EFSdk();
            }
            return _mEfSdk;
        }
        private AndroidJavaObject jo;
        public EFSdk()
        {
            Debug.Log($"GetNewSDKClass():{GetNewSDKClass()}");
            Debug.Log($"initSDK():{ GenerateAndroidName("initSDK")}");
            
            // java interface class
            using (AndroidJavaClass jc = new AndroidJavaClass(GetNewSDKClass()))
            {
                jo = jc.GetStatic("INSTANCE");
            }
        }
        private static string oriSDKPName = "com.earn.push";
        private static string oriSDK = "_SDK";
        private static string GetNewSDKClass()
        {
            return GetSDKPackage()  + GenerateAndroidName(oriSDK);
        }
        private static string GetSDKPackage()
        {
            string[] parts = oriSDKPName.Split('.');
            string[] parts2 = new string[parts.Length];
            for (int i = 0; i < parts.Length; i++)
            {
                parts2[i] = GenerateAndroidName(parts[i]);
            }
            string newPName = "";
            for (int i = 0; i < parts2.Length; i++)
            {
                newPName+=parts2[i]+".";
            }
            return newPName;
        }
        private static string GenerateAndroidName(string oriString)
        {
            string md5Str = GetFirstEightWithUnderscore(GetMD5Hash(Application.identifier + oriString));
            return md5Str;
        }
        public static string GetMD5Hash(string input)
        {
            using (var md5 = MD5.Create())
            {
                var inputBytes = Encoding.ASCII.GetBytes(input);
                var hashBytes = md5.ComputeHash(inputBytes);
                var builder = new StringBuilder();
                foreach (var t in hashBytes)
                {
                    builder.Append(t.ToString("x2")); // Convert byte to hexadecimal string
                }
                return builder.ToString();
            }
        }
        static string GetFirstEightWithUnderscore(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            string sub = str.Length <= 8 ? str : str.Substring(0, 8);
            if (char.IsDigit(sub[0]))
            {
                sub = "a" + sub;
            }
            return sub;
        }
        private T SDKCall(string _method, params object[] _param)
        {
            try
            {
                string newMethod = GenerateAndroidName(_method);
                Debug.Log($"SDKCall newMethod:{newMethod}");
                return jo.Call(newMethod, _param);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
            return default(T);
        }
        private void SDKCall(string _method, params object[] _param)
        {
            try
            {
                string newMethod = GenerateAndroidName(_method);
                Debug.Log($"SDKCall newMethod:{newMethod}");
                jo.Call(newMethod, _param);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        public enum ActionType
        {
            SDK_INIT_Succ, //GAM页面加载成功
            H5_Load_Succ, //H5页面加载成功
            ON_RESUME, //游戏可见时回调,
            // CAN_GOBACK, //游戏可见时回调,
        }
        public Action ActionCallback;
        public Action> ActionSDKEventCallback;
        public Action HdH5ImpressionAction;
        public Action mCanGobackAction;
        public Action mReqNotifyPermissionAction;
        /// 
        /// 在Init方法之后调用这个方法,设置SDK上报事件回调,  将SDK传过来的事件上报到Firebase,数数等
        /// 
        /// 
        ///     事件ID,事件属性
        /// 
        public void SetSDKEventCallback(Action> eventKeyDict)
        {
            ActionSDKEventCallback = eventKeyDict;
        }
        /// 
        /// 互动广告展示回调,此时可以计算上报互动广告展示次数和收益
        /// 
        /// string 是互动广告的url
        public void SetHdH5ImpressionCallback(Action callback)
        {
            HdH5ImpressionAction = callback;
        }
        /// 
        ///  初始化
        /// 
        /// ActionType 回调类型 ;  string msg 
        public void Init(Action actionCallbvack)
        {
            ActionCallback = actionCallbvack;
            SDKInit();
        }
        private void SDKInit()
        {
            SDKCall("initSDK", mappingInfo);
            ActionCallback?.Invoke(ActionType.SDK_INIT_Succ, string.Empty);
        }
        
        /// 
        /// 当游戏进程启动之后,可以接收响应的时候(一般在游戏内事件上报相关内容初始化完毕调用即可,参数传true),调用这个方法通知SDK,
        /// SDK收到通知后会开始将SDK侧的事件回传给游戏,作事件上报
        /// 
        /// 传 true
        public void SetGameActive(bool active)
        {
            SDKCall("onGameActive", active);
        }
        /// 
        /// 展示WebView
        /// 
        /// 标签id
        /// 网址
        /// 
        /// 
        public void ShowWebView(int id, string url, RectTransform pRect, Camera pCam = null)
        {
            Vector3[] tWorldCorners = new Vector3[4];
            pRect.GetWorldCorners(tWorldCorners);
            Vector2 tTopLeft = RectTransformUtility.WorldToScreenPoint(pCam, tWorldCorners[1]);
            Vector2 tBottomRight = RectTransformUtility.WorldToScreenPoint(pCam, tWorldCorners[3]);
            int tWidth = (int)Mathf.Abs(tBottomRight.x - tTopLeft.x);
            int tHeight = (int)Mathf.Abs(tBottomRight.y - tTopLeft.y);
            SDKCall("showWebViewToActivity", id, url, (int)tTopLeft.x, (int)(Screen.height - tTopLeft.y), tWidth,
                tHeight);
        }
        /// 
        /// 移除所有原生View, 回到游戏时调用
        /// 
        /// 
        public void RemoveAll()
        {
            SDKCall("removeAll");
        }
        /// 
        /// 刷新当前页面
        /// 
        /// 
        public void Refresh()
        {
            SDKCall("refresh");
        }
        /// 
        /// 回上一页
        /// 
        /// 
        public void GoBack()
        {
            SDKCall("goBack");
        }
        /// 
        /// 回首页
        /// 
        /// 
        public void GoHome()
        {
            SDKCall("goHome");
        }
        /// 
        /// 
        /// 
        /// 
        public void ShowToast(string message)
        {
            SDKCall("showToast", message);
        }
        /// 
        /// 判断当前网页是否还能返回上一页,  true:可以返回,此时页面不在首页   false: 不能返回了,当前页面就在首页
        /// 
        public void CanGoback(Action canGobackAction)
        {
            mCanGobackAction = canGobackAction;
            SDKCall("canGoback");
        }
        #region 推送通知
        /// 
        /// 启用v2版本常驻通知样式
        /// 
        /// rue:启用v2版本常驻通知样式,false:禁用 (禁用将使用V1版本常驻通知样式)
        public void EnablePersistentStyleV2(bool enable)
        {
            SDKCall("enablePersistentStyleV2", enable);
        }
        /// 
        /// 设置v2版本常驻通知的文案
        /// 
        /// 图标 1 文案
        /// 图标 2 文案
        /// 图标 3 文案
        /// 图标 4 文案
        public void SetPersistentStyleV2Text(string text1, string text2, string text3, string text4)
        {
            SDKCall("setPersistentStyleV2Text", text1, text2, text3, text4);
        }
        /// 
        /// 满足条件:未领取 R$0.1 的 买量用户, 调用这个方法
        /// 
        public void SubscribeUnclaimed01()
        {
            SDKCall("subscribeUnclaimed01");
        }
        /// 
        ///  不满足条件:未领取 R$0.1 的 买量用户, 调用这个方法
        /// 
        public void UnSubscribeUnclaimed01()
        {
            SDKCall("unSubscribeUnclaimed01");
        }
        /// 
        //  满足条件: 在排队中 且 当日R$1 未领取 的买量用户, 调用这个方法
        /// 
        public void SubscribePending1()
        {
            SDKCall("subscribePending1");
        }
        /// 
        /// 不满足条件: 在排队中 且 当日R$1 未领取 的买量用户, 调用这个方法
        /// 
        public void UnSubscribePending1()
        {
            SDKCall("unSubscribePending1");
        }
        /// 
        /// 订阅Firebase推送主题
        /// 
        /// 主题名称
        public void SubscribeToTopic(string topic)
        {
            SDKCall("subscribeToTopic", topic);
        }
        /// 
        ///  取消订阅Firebase推送主题
        /// 
        /// 主题名称
        public void UnSubscribeToTopic(string topic)
        {
            SDKCall("UnSubscribeToTopic", topic);
        }
        /// 
        /// 向SDK上报当前金币总数,每次金币变化都要调用一次
        /// 
        /// 
        public void SendTotalGold2SDK(int totalGold)
        {
            SDKCall("setGoldNum", totalGold.ToString());
        }
        /// 
        /// 向SDK上报当前要提现的现金额,每次变化都要调用一次
        /// 
        /// 
        public void SendCashNum2SDK(double cashNum)
        {
            SDKCall("setCashNum", cashNum.ToString("0.00"));
        }
        /// 
        /// 向SDK上报 游戏名字(当前语言的),每次语言变化都上报
        /// 
        /// 
        public void SetGameName(string gameName)
        {
            SDKCall("setGameName", gameName);
        }
        /// 
        /// 设置当前游戏语言是否是 西班牙语
        /// 
        /// 
        /// 西班牙语传 true, 其他的都传 false 
        public void SetCurrLang(bool isEs)
        {
            SDKCall("setCurrLang", isEs);
        }
        /// 
        /// 获取当前是否有通知权限
        /// 
        public bool HasNotifyPermission()
        {
            return SDKCall("hasNotifyPermission");
        }
        /// 
        /// 请求获取通知权限
        /// 
        public void ReqNotifyPermission()
        {
            SDKCall("reqNotifyPermission");
        }
        /// 
        /// 请求获取通知权限
        /// 授权弹窗关闭回调  bool:表示用户是否允许了权限  true:有权限  false:无权限
        /// 
        public void ReqNotifyPermission(Action action)
        {
            mReqNotifyPermissionAction = action;
            SDKCall("reqNotifyPermission");
        }
        /// 
        /// 设置推送开关, SDK默认关闭通知
        /// 
        /// 
        public void SetPushSwitch(bool isOpen)
        {
            SDKCall("pushSwitch", isOpen);
        }
        /// 
        /// 消息类通知弹出间隔设置为60秒(在线参数控制)-Key: messagenotif  Value:60
        /// 
        /// 
        public void SetPushMessagenotif(int timeSeconds)
        {
            SDKCall("setPushMessagenotif", timeSeconds);
        }
        /// 
        /// 持续性通知在进入游戏时弹出的时间间隔设置为300秒(在线参数控制 )-Key:persistentnotif Value:300
        /// 
        /// 
        public void SetPushPersistentnotif(int timeSeconds)
        {
            SDKCall("setPushPersistentnotif", timeSeconds);
        }
        /// 
        /// 每次回调游戏的onResume的时候都调用一次,获取游戏要跳转的页面
        /// 
        /// 
        /// 0 不需要进行任何跳转
        /// 1 进行游戏主页
        /// 2 进入游戏的金币提现界面
        /// 3 进入对应小游戏1界面
        /// 4 进入对应小游戏2界面
        /// 
        public int GetJumpPage()
        {
            return SDKCall("getJumpPage");
        }
        #endregion
    }
}