package cn.yyxx.commsdk.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebView;

import java.util.List;

import cn.yyxx.commsdk.Version;
import cn.yyxx.commsdk.base.entity.Function;
import cn.yyxx.commsdk.base.entity.SdkChargeInfo;
import cn.yyxx.commsdk.base.entity.SdkRoleInfo;
import cn.yyxx.commsdk.base.internal.ICallback;
import cn.yyxx.commsdk.base.internal.IInitialize;
import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.support.AppUtils;

/**
 * @author #Suyghur.
 * Created on 2021/12/25
 */
public final class YYXXCommSdk {

    private static final long CLICK_INTERVAL = 1500L;
    private Object mSdkBridge = null;
    private long clickLoginTime = 0L;
    private long clickLogoutTime = 0L;
    private long clickChargeTime = 0L;

    private String processName = "";
    private boolean doSdkInit = false;

    private YYXXCommSdk() {

    }

    public static YYXXCommSdk getInstance() {
        return YYXXCommSdkHolder.INSTANCE;
    }


    private static final class YYXXCommSdkHolder {
        private static final YYXXCommSdk INSTANCE = new YYXXCommSdk();

        /**
         * 防止单例对象在反序列化时重新生成对象
         */
        private static Object readResolve() {
            return INSTANCE;
        }
    }

    private Object getSdkBridgeManager(Context context) {
        if (null == mSdkBridge) {
            mSdkBridge = SdkBridgeManager.initSdkBridgeManager(context);
        }
        return mSdkBridge;
    }

    /**
     * 同步Application中的attachBaseContext
     *
     * @param application Application上下文对象
     * @param context     Context上下文对象
     */
    public void attachBaseContext(Application application, Context context) {
        if (TextUtils.isEmpty(processName)) {
            processName = AppUtils.getProcessName(context);
        }
        if (TextUtils.isEmpty(processName) || !processName.equals(context.getPackageName())) {
            return;
        }
        if (mSdkBridge == null) {
            mSdkBridge = getSdkBridgeManager(context);
        }
        SdkBridgeManager.call(Function.ATTACH_BASE_CONTEXT, new Class[]{Application.class, Context.class}, new Object[]{application, context});
    }

    /**
     * 同步Application中的onCreate
     *
     * @param application Application上下文对象
     */
    public void initApplication(Application application) {
        if (TextUtils.isEmpty(processName)) {
            processName = AppUtils.getProcessName(application);
        }
        if (TextUtils.isEmpty(processName) || !processName.equals(application.getPackageName())) {
            return;
        }
        //适配Android P WebView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try {
                if (!application.getPackageName().equals(processName)) {
                    Logger.d("Android P 设置webView不同的目录");
                    WebView.setDataDirectorySuffix(processName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (mSdkBridge == null) {
            mSdkBridge = getSdkBridgeManager(application);
        }
        SdkBridgeManager.call(Function.INIT_APPLICATION, new Class[]{Application.class}, new Object[]{application});
    }

    /**
     * 启动打开隐私协议页面
     * @param activity
     * @param callback
     */
    public void  initAgreement(Activity activity, final ICallback callback){
        if (checkSdkBridgeNull(Function.INIT_AGREEMENT, callback)) {
            return;
        }

        SdkBridgeManager.call(Function.INIT_AGREEMENT, new Class[]{Activity.class, ICallback.class}, new Object[]{activity, callback});


    }

    /**
     * SDK初始化
     *
     * @param activity    Activity上下文
     * @param isLandscape 是否横屏
     * @param callback    SDK初始化回调
     */
    public void initialize(Activity activity, Boolean isLandscape, final ICallback callback) {
        if (checkSdkBridgeNull(Function.INITIALIZE, callback)) {
            return;
        }

        //有些CP自己请求了权限，导致回调权限2次，执行2次initFuseSdk，这里拦截一下
        if (doSdkInit) {
            Logger.e("QSGameSdk initialize 已经执行，拦截此次调用");
            return;
        }

        SdkBridgeManager.call(Function.INITIALIZE, new Class[]{Activity.class, Boolean.class,  ICallback.class}, new Object[]{activity, isLandscape, callback});
    }

    /**
     * SDK用户登录
     *
     * @param activity Activity上下文
     * @param callback 登录回调对象
     */
    public void login(Activity activity, ICallback callback) {
        if (checkSdkBridgeNull(Function.LOGIN, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.LOGIN, callback)) {
            return;
        }

        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            Logger.e("调用登录接口太频繁，拦截此次操作");
            return;
        }
        clickLoginTime = System.currentTimeMillis();
        SdkBridgeManager.call(Function.LOGIN, new Class[]{Activity.class, ICallback.class}, new Object[]{activity, callback});
    }

    /**
     * SDK用户登出账号
     *
     * @param activity Activity上下文
     * @param callback 登出回调对象
     */
    public void logout(Activity activity, ICallback callback) {
        if (checkSdkBridgeNull(Function.LOGOUT, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.LOGOUT, callback)) {
            return;
        }

        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            Logger.e("调用登录接口后，调用登出账号接口间隔太短，拦截此次操作");
            return;
        }
        if (System.currentTimeMillis() - clickLogoutTime < CLICK_INTERVAL) {
            Logger.e("调用登出账号接口太频繁，拦截此次操作");
            return;
        }
        clickLogoutTime = System.currentTimeMillis();
        SdkBridgeManager.call(Function.LOGOUT, new Class[]{Activity.class, ICallback.class}, new Object[]{activity, callback});
    }

    /**
     * SDK用户支付
     *
     * @param activity   Activity上下文
     * @param chargeInfo 支付信息实体对象
     * @param callback   支付回调对象
     */
    public void charge(Activity activity, SdkChargeInfo chargeInfo, ICallback callback) {
        if (checkSdkBridgeNull(Function.CHARGE, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.CHARGE, callback)) {
            return;
        }

        if (System.currentTimeMillis() - clickChargeTime < CLICK_INTERVAL) {
            Logger.e("调用充值接口太频繁，拦截此次操作");
            return;
        }
        clickChargeTime = System.currentTimeMillis();
        SdkBridgeManager.call(Function.CHARGE, new Class[]{Activity.class, SdkChargeInfo.class, ICallback.class}, new Object[]{activity, chargeInfo, callback});
    }


    /**
     * SDK角色创建信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     * @param callback 角色信息上报回调对象
     */
    public void roleCreate(Activity activity, SdkRoleInfo roleInfo, ICallback callback) {
        if (checkSdkBridgeNull(Function.ROLE_CREATE, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.ROLE_CREATE, callback)) {
            return;
        }
        SdkBridgeManager.call(Function.ROLE_CREATE, new Class[]{Activity.class, SdkRoleInfo.class, ICallback.class}, new Object[]{activity, roleInfo, callback});
    }

    /**
     * SDK角色登录信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     * @param callback 角色信息上报回调对象
     */
    public void roleLauncher(Activity activity, SdkRoleInfo roleInfo, ICallback callback) {
        if (checkSdkBridgeNull(Function.ROLE_LAUNCHER, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.ROLE_LAUNCHER, callback)) {
            return;
        }
        SdkBridgeManager.call(Function.ROLE_LAUNCHER, new Class[]{Activity.class, SdkRoleInfo.class, ICallback.class}, new Object[]{activity, roleInfo, callback});
    }

    /**
     * SDK角色升级信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     * @param callback 角色信息上报回调对象
     */
    public void roleUpgrade(Activity activity, SdkRoleInfo roleInfo, ICallback callback) {
        if (checkSdkBridgeNull(Function.ROLE_UPGRADE, callback)) {
            return;
        }

        if (checkSdkNonInit(Function.ROLE_UPGRADE, callback)) {
            return;
        }
        SdkBridgeManager.call(Function.ROLE_UPGRADE, new Class[]{Activity.class, SdkRoleInfo.class, ICallback.class}, new Object[]{activity, roleInfo, callback});
    }

    /**
     * 是否显示SDK退出框
     *
     * @param activity Activity上下文
     */
    public Boolean hasExitView(Activity activity) {
        if (checkSdkBridgeNull(Function.HAS_EXIT_VIEW, null)) {
            return false;
        }

        if (checkSdkNonInit(Function.HAS_EXIT_VIEW, null)) {
            return false;
        }

        return (Boolean) SdkBridgeManager.callback(Function.HAS_EXIT_VIEW, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 显示退出框
     *
     * @param activity Activity上下文
     * @param callback 退出回调对象
     */
    public void openExitView(Activity activity, ICallback callback) {
        if (checkSdkBridgeNull(Function.OPEN_EXIT_VIEW, null)) {
            return;
        }

        if (checkSdkNonInit(Function.OPEN_EXIT_VIEW, null)) {
            return;
        }

        SdkBridgeManager.call(Function.OPEN_EXIT_VIEW, new Class[]{Activity.class, ICallback.class}, new Object[]{activity, callback});
    }

    /**
     * 同步游戏Activity的onStart
     */
    public void onStart(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_START, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_START, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onRestart
     */
    public void onRestart(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_RESTART, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_RESTART, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onResume
     */
    public void onResume(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_RESUME, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_RESUME, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onPause
     */
    public void onPause(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_PAUSE, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_PAUSE, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onStop
     */
    public void onStop(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_STOP, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_STOP, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onDestroy
     */
    public void onDestroy(Activity activity) {
        if (checkSdkBridgeNull(Function.ON_DESTROY, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_DESTROY, new Class[]{Activity.class}, new Object[]{activity});
    }

    /**
     * 同步游戏Activity的onActivityResult
     */
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
        if (checkSdkBridgeNull(Function.ON_ACTIVITY_RESULT, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_ACTIVITY_RESULT,
                new Class[]{Activity.class, Integer.class, Integer.class, Intent.class},
                new Object[]{activity, requestCode, resultCode, intent});
    }

    /**
     * 同步游戏Activity的onNewIntent
     */
    public void onNewIntent(Activity activity, Intent intent) {
        if (checkSdkBridgeNull(Function.ON_NEW_INTENT, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_NEW_INTENT, new Class[]{Activity.class, Intent.class}, new Object[]{activity, intent});
    }

    /**
     * 权限请求
     *
     * @param activity    Activity上下文
     * @param permissions 权限列表
     * @param callback    权限请求回调对象
     */
    public void requestPermission(Activity activity, List<String> permissions, ICallback callback) {
        if (checkSdkBridgeNull(Function.REQUEST_PERMISSION, null)) {
            return;
        }
        SdkBridgeManager.call(Function.REQUEST_PERMISSION,
                new Class[]{Activity.class, List.class, ICallback.class},
                new Object[]{activity, permissions, callback});
    }



    public void onConfigurationChanged(Configuration newConfigs) {
        if (checkSdkBridgeNull(Function.ON_CONFIGURATION_CHANGED, null)) {
            return;
        }
        SdkBridgeManager.call(Function.ON_CONFIGURATION_CHANGED, new Class[]{Intent.class}, new Object[]{newConfigs});
    }


    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
        if (checkSdkBridgeNull(Function.ON_REQUEST_PERMISSIONS_RESULT, null)) {
            return;
        }

        SdkBridgeManager.call(Function.ON_REQUEST_PERMISSIONS_RESULT, new Class[]{int.class,String[].class,int[].class}, new Object[]{requestCode,permissions,grantResults});
    }


    public String getCurrentOpenId() {
        if (checkSdkBridgeNull(Function.GET_CURRENT_USER_ID, null)) {
            return "";
        }

        if (checkSdkNonInit(Function.GET_CURRENT_USER_ID, null)) {
            return "";
        }

        return (String) SdkBridgeManager.callback(Function.GET_CURRENT_USER_ID, null, null);
    }

    public String getCurrentSdkVersion() {
        return Version.VERSION_NAME;
    }

    private boolean checkSdkBridgeNull(String function, ICallback callback) {
        if (mSdkBridge == null) {
            Logger.e("invoke " + function + " error ... SdkBridge is null");
            if (callback != null) {
                callback.onResult(-1, "YYXXCommSdk初始化失败");
            }
            return true;
        } else {
            return false;
        }
    }

    private boolean checkSdkNonInit(String function, ICallback callback) {
        if (!doSdkInit) {
            Logger.e("invoke " + function + " error ... QSGameSdk not initialized yet");
            if (callback != null) {
                callback.onResult(-1, "QSGameSdk还未进行初始化");
            }
            return true;
        } else {
            return false;
        }
    }
}
