package com.yyrh.sdk;

import static com.yyrh.constant.URLConstants.RECHARGEINT;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;

import com.yyrh.advertisement.AdSdkCallback;
import com.yyrh.advertisement.AdvertiseManager;
import com.yyrh.constant.RoleInfo;
import com.yyrh.constant.SDKSettings;
import com.yyrh.easypermission.EasyPermission;
import com.yyrh.easypermission.GrantResult;
import com.yyrh.easypermission.Permission;
import com.yyrh.easypermission.PermissionRequestListener;
import com.yyrh.factory.SdkManager;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.callback.ExitCallback;
import com.yyrh.sdk.callback.InitCallback;
import com.yyrh.sdk.callback.LoginCallback;
import com.yyrh.sdk.callback.LogoutCallback;
import com.yyrh.sdk.callback.PayCallback;
import com.yyrh.sdk.callback.PayOrderCallback;
import com.yyrh.sdk.callback.RealNameMsgCallback;
import com.yyrh.sdk.callback.UserPolicyCallback;
import com.yyrh.ui.dialog.GameSplashDialog;
import com.yyrh.utils.PermissionUtils;
import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.TosUtil;
import com.yyrh.utils.Utils;
import com.yyrh.utils.YYLog;
import com.yythird.sdk.ChannelSDK;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SDKEntry {

    private InitCallback initCall;
    private LoginCallback loginCall;
    private PayCallback payCall;
    private LogoutCallback logoutCall;
    private ExitCallback exitCall;
    public RealNameMsgCallback realNameMsgCallback;
    public Activity gameAct;

    private UserPolicyCallback userPolicyCallback;
    private ChannelSDK channelSDKImpl = null;

    private YyrhSdkManager manager = null;

    private String role_ctime = "";

    private List<String> permissionList = new ArrayList<String>(Arrays.asList(Permission.READ_PHONE_STATE, Permission.WRITE_EXTERNAL_STORAGE));

    //广告操作回调
    public AdSdkCallback adSdkCallback = new AdSdkCallback() {
        @Override
        public void onRegisterSuccess(String msg) {

            AdvertiseManager.defaultManager(gameAct).registration(gameAct, msg);
        }

        @Override
        public void onLoginSuccess(String msg) {
            AdvertiseManager.defaultManager(gameAct).login(gameAct, msg);
        }

        @Override
        public void onPaySuccess(HashMap<String, Object> map) {
            AdvertiseManager.defaultManager(gameAct).paymentFinish(gameAct, map);
        }

        @Override
        public void onCreateOrder(HashMap<String, Object> map) {
            AdvertiseManager.defaultManager(gameAct).callPayment(gameAct, map);
        }

        @Override
        public void onUpLoadRoleInfo(String type, RoleInfo roleInfo) {
            AdvertiseManager.defaultManager(gameAct).upLoadRoleInfo(gameAct, type, roleInfo);
        }

        @Override
        public void onResume(Activity activity) {
            AdvertiseManager.defaultManager(activity).onResume(activity);
        }

        @Override
        public void onPause(Activity activity) {
            AdvertiseManager.defaultManager(activity).onPause(activity);
        }

        @Override
        public void onDestroy(Activity activity) {
            AdvertiseManager.defaultManager(activity).onDestroy(activity);

        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            AdvertiseManager.defaultManager(gameAct).onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        @Override
        public void onExitGame(Activity activity) {
            AdvertiseManager.defaultManager(activity).onExitGame(activity);
        }

        @Override
        public void onReportAdEvent(String event, JSONObject json) {
            AdvertiseManager.defaultManager(gameAct).reportAdEvent(event, json);
        }
    };


    //自有SDK回调
    public SdkCallback sdkCallback = new SdkCallback() {
        @Override
        public void onSetChannelTagCallback(String msg) {

        }

        @Override
        public void onInitCallback(boolean success, String msg) {
            if (success) {
                initCall.onInitSuccess(msg);

            } else {

                new TosUtil(gameAct, TosUtil.TOAST_ERROR, msg).show();

                initCall.onInitFailed(msg);

            }

        }

        @Override
        public void onLoginChannelCallback(String msg) {
            NetRequestApi.loginWithChannel(gameAct, msg, loginCall);
        }

        @Override
        public void onLogOutCallback(String msg) {
            logoutCall.onLogoutSuccess();
        }

        @Override
        public void onPayFinishCallback(boolean success, String msg) {
            if (success) {
                payCall.onPaySuccess(msg);
            } else {
                payCall.onPayFailed(msg);
            }
        }

        @Override
        public void onExiGameCallback(boolean success, String msg) {
            exitCall.onExit(true);
        }

        @Override
        public void onPayExtParamCallback(HashMap<String, String> payInfo, String url) {
            NetRequestApi.payChannelNotify(payInfo, url);
        }

        @Override
        public void onGetChannelRealNameCallback(boolean isRealName, String report_type, String birthday) {
            if (isRealName) {
                NetRequestApi.recordUserRealNameInfo(gameAct, report_type, birthday);
            } else {
                realNameMsgCallback.onLoadRealNameMsg(false, "");
            }
        }

        @Override
        public void onLoginChannelFail(String msg) {
            new TosUtil(gameAct, TosUtil.TOAST_ERROR, msg).show();
            channelSDKImpl.SDKLoginChannelFail(msg);
        }

        @Override
        public void onLoginChannelSuccess(String msg) {
            channelSDKImpl.SDKLoginChannelSuccess(msg);
        }

        @Override
        public void onUploadUserRealNameInfo(String report_type, String msg) {
            NetRequestApi.upLoadUserRealNameInfo(report_type, msg);
        }

        @Override
        public void onGetOaidCallback(final boolean isSuccess, final String oaid) {
//            YYLog.d("onGetOaidCallback");
//            if (isSuccess) {
//                if (Build.VERSION.SDK_INT > 28) {
//                    SdkNativeBoost.getInstance().setParam("ifa_type", "2");
//                    initCall.onGetOaid(true, oaid);
//                } else {
//                    SdkNativeBoost.getInstance().setParam("ifa_type", "0");
//                    initCall.onGetOaid(false, "");
//                }
//                SdkNativeBoost.getInstance().setParam("ifa", oaid);
//                Utils.setSharedPreferences("yyrh", "simulateImei", oaid, gameAct);
//            } else {
//                SdkNativeBoost.getInstance().setParam("ifa", DeviceInfoUtils.getImei(gameAct));
//                initCall.onGetOaid(false, "");
//            }
//            manager.yyrhInit(gameAct);
        }


        @Override
        public String onGetChannelUid() {
            return SDKSettings.loginData.channel_uid;
        }

        @Override
        public void onShowGameExit() {
            initCall.onShowGameExit();
        }

        @Override
        public void onShowPolicyAgree() {
            userPolicyCallback.onAgree();
        }

        @Override
        public void onShowPolicyDisagree() {
            userPolicyCallback.onDisagree();
        }

        @Override
        public void onShowPolicyHide() {
            userPolicyCallback.onHide();
        }

        @Override
        public void onShowPolicyError() {
            userPolicyCallback.onError();
        }

        @Override
        public void onLoginSuccess(String token) {
            YYLog.i(SDKSettings.loginData.toString());
            loginCall.onLoginSuccess(token);
            SDKEntry.getSdkInstance().adSdkCallback.onLoginSuccess(SDKSettings.loginData.uname);
        }

        @Override
        public void onLoginFailed(String msg) {
            loginCall.onLoginFailed(msg);
        }

        @Override
        public void onLoginError(String msg) {
            loginCall.onLoginError(msg);
        }

        @Override
        public void realNameMsgCallback(boolean isRealName, String birthday) {
            realNameMsgCallback.onLoadRealNameMsg(isRealName, birthday);
        }

    };

    /**
     * 实现单例
     */
    private SDKEntry() {
    }

    public static SDKEntry getSdkInstance() {
        return SDKEntryHolder.INSTANCE;
    }

    public void attachBaseContext(Application application, Context context){
        SdkManager.defaultManager().attachBaseContext(application, context);
    }

    public void initApplication(Application application){
        SdkManager.defaultManager().initApplication(application);
    }

    public void initSdk(final Activity activity, final InitCallback callback, final boolean isDebug) {
        this.gameAct = activity;
        this.initCall = callback;

        InputStream inputStream = null;

        try {
            inputStream = activity.getAssets().open("yyrh_start_image.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (inputStream != null) {
            new GameSplashDialog(activity, ResourceUtil.getStyleId(activity, "hnyy_welcome_dialog")).show();
        }

        int checkResult;
        if (PermissionUtils.checkIsHasPermission(activity, PermissionUtils.CODE_READ_PHONE_STATE) == 0 && PermissionUtils.checkIsHasPermission(activity, PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE) == 0) {
            checkResult = 0;
        } else {
            checkResult = -1;
        }
        switch (checkResult) {
            case 0:
                AdvertiseManager.defaultManager(activity).advertiseInit(activity);
                SdkManager.defaultManager().initSdk(activity, callback, isDebug);
                break;
            case -1:

                String[] permissions = permissionList.toArray(new String[0]);

                EasyPermission.with(activity)
                        .addPermissions(permissions)          //申请打电话权限
                        .request(new PermissionRequestListener() {
                            @Override
                            public void onGrant(Map<String, GrantResult> result) {
                                //权限申请返回
                                AdvertiseManager.defaultManager(activity).advertiseInit(activity);
                                SdkManager.defaultManager().initSdk(activity, callback,isDebug);
                            }

                            @Override
                            public void onCancel(String stopPermission) {
                                //在addRequestPermissionRationaleHandler的处理函数里面调用了NextAction.next(NextActionType.STOP,就会中断申请过程，直接回调到这里来

                            }
                        });
                break;
        }


    }

    public void setExtPermission(ArrayList<String> extPermission) {
        if (extPermission != null) {
            for (String permission : extPermission) {
                permissionList.add(permission);
            }
        }
    }

    public void login(Activity activity, LoginCallback callback) {
        this.loginCall = callback;
        SdkManager.defaultManager().login(activity, callback);
    }

    public void setSDKLogoutListener(Activity activity, final LogoutCallback callback) {
        YYLog.i("setSDKLogoutListener");
        logoutCall = callback;
        SdkManager.defaultManager().setSDKLogoutListener(activity, callback);
    }

    public void logout() {
        YYLog.i("logout");
        SdkManager.defaultManager().logOut();
    }

    public void upLoadRoleInfo(String type, Activity activity, RoleInfo roleInfo) {
        YYLog.i("sdk uploadUserInfo");

        this.role_ctime = roleInfo.getRoleCreateTime();
        String roleId = roleInfo.getRoleId();
        String roleName = roleInfo.getRoleName();
        String roleLevel = roleInfo.getRoleLevel();
        String gender = roleInfo.getGender();
        String serverId = roleInfo.getServerId();
        String serverName = roleInfo.getServerName();
        String hasGold = roleInfo.getHasGold();
        String vipLevel = roleInfo.getVipLevel();
        String roleCreateTime = roleInfo.getRoleCreateTime();
        String partyName = roleInfo.getPartyName();
        String role_power = roleInfo.getRolePower();
        String partyId = roleInfo.getPartyId();
        String reincarnationCount = roleInfo.getReincarnationCount();
        String charge = roleInfo.getCharge();
        if (TextUtils.isEmpty(charge)) {
            charge = "0";
        }

        if (TextUtils.isEmpty(roleId)
                || TextUtils.isEmpty(roleName)
                || TextUtils.isEmpty(roleLevel)
                || TextUtils.isEmpty(gender)
                || TextUtils.isEmpty(serverId)
                || TextUtils.isEmpty(serverName)
                || TextUtils.isEmpty(hasGold)
                || TextUtils.isEmpty(vipLevel)
                || TextUtils.isEmpty(roleCreateTime)
                || TextUtils.isEmpty(role_power)
                || TextUtils.isEmpty(reincarnationCount)) {

            YYLog.i("上报参数有空值，请检查: " + roleInfo.getAllParam());

        } else {
            YYLog.i("游戏角色信息上报sdk相关参数: " + roleInfo.getAllParam());

            SdkManager.defaultManager().uploadRoleInfo(type, activity, roleInfo);
            adSdkCallback.onUpLoadRoleInfo(type, roleInfo);
        }
    }

    public void pay(final HashMap<String, Object> map, final PayCallback callback, final Activity activity) {
        this.payCall = callback;
        YYLog.i("payOrderInit");

        for (String key :map.keySet()){
            YYLog.i("key: "+key+" ,value: "+map.get(key));
        }

        SdkManager.defaultManager().pay(activity,map);
//
//        if (channelSDKImpl.SDKGetPstatus()) {
//            SdkManager.defaultManager().forcePay(activity, map);
//            return;
//        }
//        NetRequestApi.payOrderInit(RECHARGEINT, map, activity, new PayOrderCallback() {
//
//
//            @Override
//            public void onPaySuccess(HashMap<String, Object> map) {
//
//
//                adSdkCallback.onCreateOrder(map);
//                SdkManager.defaultManager().pay(activity, map);
//
//            }
//
//            @Override
//            public void onPayFailed(String msg) {
//                callback.onPayFailed(msg);
//            }
//
//        });
    }

    public void exitGame(Activity activity, ExitCallback callback) {
        YYLog.i("exitGame");
        this.exitCall = callback;
        SdkManager.defaultManager().exit(activity, callback);
    }


    public void reportAdEvent(String event, JSONObject json) {
        YYLog.i("game event :" + event + " and json: " + json.toString());
        SdkManager.defaultManager().reportAdEvent(event, json);
    }

    /**
     * 生命周期
     */
    public void sdkOnStart(Activity activity) {
        YYLog.i("sdk OnStart");
        SdkManager.defaultManager().sdkOnStart(activity);
    }


    public void sdkOnCreate(Activity activity, Bundle savedInstanceState) {
        YYLog.i("sdk onCreate");

        SdkManager.defaultManager().sdkOnCreate(activity, savedInstanceState);
    }

    public void sdkOnPause(Activity activity) {
        YYLog.i("sdk OnPause");
        SDKEntry.getSdkInstance().adSdkCallback.onPause(activity);
        SdkManager.defaultManager().sdkOnPause(activity);


    }

    public void sdkOnResume(Activity activity) {
        YYLog.i("sdk OnResume");
        SDKEntry.getSdkInstance().adSdkCallback.onResume(activity);
        SdkManager.defaultManager().sdkOnResume(activity);

    }

    public void sdkOnRestart(Activity activity) {
        YYLog.i("sdk onRestart");
        SdkManager.defaultManager().sdkOnRestart(activity);
    }


    public void sdkOnNewIntent(Activity acitivty, Intent intent) {
        YYLog.i("sdk OnNewIntent");
        SdkManager.defaultManager().sdkOnNewIntent(acitivty, intent);

    }

    public void sdkOnStop(Activity activity) {
        YYLog.i("sdk OnStop");
        SdkManager.defaultManager().sdkOnStop(activity);
    }

    public void onConfigurationChanged(Configuration newConfigs) {
        YYLog.i("sdk onConfigurationChanged");
        SdkManager.defaultManager().onConfigurationChanged(newConfigs);
    }


    public void sdkOnDestroy(Activity activity) {
        YYLog.i("sdk OnDestroy");
        SDKEntry.getSdkInstance().adSdkCallback.onDestroy(activity);
        SdkManager.defaultManager().sdkOnDestroy(activity);


    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        YYLog.i("sdk onRequestPermissionsResult");
        SDKEntry.getSdkInstance().adSdkCallback.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SdkManager.defaultManager().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void onActivityResult(Activity ac, int requestCode, int resultCode, Intent data) {
        YYLog.i("sdk onActivityResult");
        SdkManager.defaultManager().onActivityResult(ac, requestCode, resultCode, data);


    }

    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
        YYLog.i("sdk onWindowFocusChanged");
        SdkManager.defaultManager().onWindowFocusChanged(activity, hasFocus);
    }


    public void getRealNameInfo(Activity activity, RealNameMsgCallback realNameMsgCallback) {
        this.realNameMsgCallback = realNameMsgCallback;
        if (Utils.getTextIsNull(SDKSettings.loginData.uname)) {
            new TosUtil(activity, TosUtil.TOAST_ERROR, activity.getString(ResourceUtil.getStringId(activity, "hnyy_login2pay"))).show();
            return;
        }
        SdkManager.defaultManager().getRealNameInfo(activity, realNameMsgCallback);
    }

    public void showPrivacyPolicy(Activity activity, UserPolicyCallback userPolicyCallback) {
        this.userPolicyCallback = userPolicyCallback;
        YyrhSdkManager.defaultManager().yyrhShowPolicy(activity, userPolicyCallback);
    }

    public String getCurrentUserId() {
        return SdkManager.defaultManager().getCurrentUserId();
    }

    private static final class SDKEntryHolder {
        private static final SDKEntry INSTANCE = new SDKEntry();
    }
}
