package com.yyrh.factory;

import static com.yyrh.constant.Constants.CLICK_INTERVAL;
import static com.yyrh.constant.URLConstants.PAYMENTWAY;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.dolin.zap.Zap;
import com.yyrh.constant.RoleInfo;
import com.yyrh.core.SDKDrive;
import com.yyrh.core.entity.ResultInfo;
import com.yyrh.core.entity.bean.InitBean;
import com.yyrh.core.internal.IRequestCallback;
import com.yyrh.core.network.Host;
import com.yyrh.core.network.SdkRequest;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.SDKEntry;
import com.yyrh.sdk.SdkCallback;
import com.yyrh.sdk.YyrhSdkManager;
import com.yyrh.sdk.callback.InitCallback;
import com.yyrh.sdk.callback.LoginCallback;
import com.yyrh.sdk.callback.PayOrderCallback;
import com.yyrh.sdk.callback.RealNameMsgCallback;
import com.yyrh.utils.FileUtils;
import com.yyrh.utils.MMKVUtils;
import com.yyrh.utils.YYLog;
import com.yythird.base.ChannelSdkCallback;
import com.yythird.sdk.ChannelSDK;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import cn.yyxx.support.device.DeviceInfoUtils;

public class SdkManager {

    private static SdkManager manager = null;

    private ISdkOperation operation;

    private InitCallback initCallback = null;
    private LoginCallback loginCallback = null;

    private long clickLoginTime = 0L;

    public InitBean initBean = null;
    public String channelTag = "";
    public boolean isLandscape = false;
    private static boolean hasReadIds = false;
    private static String deviceIds = "";


    private final AtomicInteger timeCount = new AtomicInteger(0);

    public final SdkCallback sdkCallback = new SdkCallback() {
        @Override
        public void onShowPolicyAgree() {

        }

        @Override
        public void onShowPolicyDisagree() {

        }

        @Override
        public void onShowPolicyHide() {

        }

        @Override
        public void onShowPolicyError() {

        }

        @Override
        public void onLoginSuccess(String token) {

        }

        @Override
        public void onLoginFailed(String msg) {

        }

        @Override
        public void onLoginError(String msg) {

        }

        @Override
        public void realNameMsgCallback(boolean isRealName, String birthday) {

        }

        @Override
        public void onSetChannelTagCallback(String msg) {

        }

        @Override
        public void onInitCallback(boolean success, String msg) {

        }

        @Override
        public void onLoginChannelCallback(String msg) {

        }

        @Override
        public void onLogOutCallback(String msg) {

        }

        @Override
        public void onPayFinishCallback(boolean success, String msg) {

        }

        @Override
        public void onExiGameCallback(boolean success, String msg) {

        }

        @Override
        public void onPayExtParamCallback(HashMap<String, String> payInfo, String url) {

        }

        @Override
        public void onGetChannelRealNameCallback(boolean isRealName, String report_type, String birthday) {

        }

        @Override
        public void onLoginChannelFail(String msg) {

        }

        @Override
        public void onLoginChannelSuccess(String msg) {

        }

        @Override
        public void onUploadUserRealNameInfo(String report_type, String msg) {

        }

        @Override
        public void onGetOaidCallback(boolean isSuccess, String oaid) {
            // 获取ids回调
            deviceIds = oaid;
            if (isSuccess) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                    initCallback.onGetOaid(true, oaid);
                } else {
                    initCallback.onGetOaid(false, "");
                }
            } else {
                initCallback.onGetOaid(false, "");
            }
            SDKDrive.getInstance().setParam("ifa", oaid);
            hasReadIds = true;
            YYLog.d("device ids initialize finish...");
        }

        @Override
        public String onGetChannelUid() {
            return null;
        }

        @Override
        public void onShowGameExit() {

        }
    };

    private SdkManager() {
    }

    public static SdkManager defaultManager() {
        if (manager == null) {
            synchronized (SdkManager.class) {
                if (manager == null) {
                    manager = new SdkManager();
                }
            }
        }
        return manager;
    }

    /**
     * operation
     */
    public void onInitSuccess(Activity activity) {
        operation = SdkFactory.GetSdk();
    }

    public void attachBaseContext(Application application, Context context) {
        YYLog.initZap(application);
        SDKDrive.getInstance().initDrive(application);
        if (Host.BASEURL.equals("https://sdkapi.ykklayo.com")) {
            Host.MODEL = 1;
        } else {
            Host.MODEL = 0;
        }
    }

    public void initApplication(Application application) {
        MMKVUtils.getInstance().init(application);
        this.channelTag = FileUtils.readAssetsFileByKey(application, "YyrhParam.cnf", "CHANNELTAG");
    }

    public void initSdk(final Activity activity, final InitCallback callback, boolean isDebug) {
        this.initCallback = callback;
        int orientation = activity.getRequestedOrientation();
        this.isLandscape = orientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT &&
                orientation != ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
        ChannelSDK.getInstance().SDKInit(activity, sdkCallback);
        initDeviceInfo(activity);

        if (!hasReadIds) {
            YYLog.e("还未完成设备信息加载，将延迟初始化");
            // TODO showDialog
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!hasReadIds) {
                        try {
                            YYLog.e("还未完成设备信息加载，将延迟1s初始化");
                            Thread.sleep(1000);
                            timeCount.getAndIncrement();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(deviceIds)) {
                                YYLog.e("加载设备信息失败，共延迟" + timeCount + "s初始化，将进行初始化操作...");
                            } else {
                                YYLog.i("加载设备信息成功，共延迟" + timeCount + "s初始化，将进行初始化操作...");
                            }
                            // TODO hideDialog
                            startSdkInit(activity, callback);
                        }
                    });
                }
            }).start();
        } else {
            YYLog.i("加载设备信息成功，开始初始化...");
            startSdkInit(activity, callback);
        }
    }

    private void initDeviceInfo(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            SDKDrive.getInstance().setParam("ifa_type", "2");
            ChannelSDK.getInstance().SDKGetOaid();
        } else {
            String ids = "";
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // 没有授权用android id
                ids = DeviceInfoUtils.getAndroidDeviceId(activity);
                SDKDrive.getInstance().setParam("ifa_type", "3");
            } else {
                // 如果授权了
                ids = DeviceInfoUtils.getImei(activity);
                SDKDrive.getInstance().setParam("ifa_type", "1");
            }
            sdkCallback.onGetOaidCallback(true, ids);
        }
    }

    private void startSdkInit(Activity activity, final InitCallback callback) {
        SdkRequest.initSdk(activity, new IRequestCallback() {
            @Override
            public void onResponse(ResultInfo resultInfo) {
                if (resultInfo.code == 1) {
                    // 初始化成功
                    initBean = InitBean.toBean(resultInfo.data);
                    YYLog.d("bean: " + initBean.toString());
                    initSdkOperation();
                    callback.onInitSuccess("sdk初始化成功");
                } else {
                    if (TextUtils.isEmpty(resultInfo.msg)) {
                        callback.onInitFailed("sdk初始化失败");
                    } else {
                        callback.onInitFailed(resultInfo.msg);
                    }
                }
            }
        });
    }

    private void initSdkOperation() {
        if (initBean.sdkLogin == 1 && !channelTag.equals("YYRHSDK")) {
            this.operation = new ChannelSdkOperation();
        } else {
            this.operation = new YyrhSdkOperation();
        }
    }

    public void login(Activity activity) {
        if (operation == null) {
            return;
        }
        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            YYLog.i("调用登录接口太频繁，拦截此次操作");
            return;
        }
        clickLoginTime = System.currentTimeMillis();
        operation.login(activity);
    }

    public void uploadRoleInfo(String type, Activity activity, RoleInfo roleInfo) {
        if (operation == null) {
            return;
        }
        operation.uploadRoleInfo(type, activity, roleInfo);

    }

    public void reportAdEvent(String event, JSONObject json) {
        if (operation == null) {
            return;
        }
        operation.reportAdEvent(event, json);
    }

    public void pay(Activity activity, HashMap<String, Object> map) {
        if (operation == null) {
            return;
        }
        operation.pay(activity, map);
    }

    public void forcePay(final Activity activity, HashMap<String, Object> map) {
        NetRequestApi.payOrderInit(PAYMENTWAY, map, activity, new PayOrderCallback() {
            @Override
            public void onPaySuccess(HashMap<String, Object> map) {
                SDKEntry.getSdkInstance().adSdkCallback.onCreateOrder(map);
                YyrhSdkManager.defaultManager().yyrhPay(activity, map);
            }

            @Override
            public void onPayFailed(String msg) {
                SDKEntry.getSdkInstance().sdkCallback.onPayFinishCallback(false, msg);
            }
        });
    }

    public void exit(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.exit(activity);
    }

    public void logOut() {
        if (operation == null) {
            return;
        }
        operation.logOut();
    }

    public void getRealNameInfo(Activity activity, RealNameMsgCallback realNameMsgCallback) {
        if (operation == null) {
            return;
        }
        operation.getRealNameInfo(activity, realNameMsgCallback);
    }

    public void setSDKLogoutListener(Activity ac, ChannelSdkCallback sdkCallback) {
        if (operation == null) {
            return;
        }
        operation.setSDKLogoutListener(ac, sdkCallback);
    }


    /**
     * 生命周期
     */
    public void sdkOnStart(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnStart(activity);
    }

    public void sdkOnCreate(Activity activity, Bundle savedInstanceState) {
        if (operation == null) {
            return;
        }
        operation.sdkOnCreate(activity, savedInstanceState);
    }

    public void sdkOnPause(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnPause(activity);
    }

    public void sdkOnResume(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnResume(activity);
    }

    public void sdkOnRestart(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnRestart(activity);
    }

    public void sdkOnStop(Activity activity) {
        if (operation == null) {
            return;
        }
        operation.sdkOnStop(activity);
    }


    public void sdkOnDestroy(Activity activity) {
        Zap.recycle();
        if (operation == null) {
            return;
        }
        operation.sdkOnDestroy(activity);
    }


    public void sdkOnNewIntent(Activity activity, Intent intent) {
        if (operation == null) {
            return;
        }
        operation.sdkOnNewIntent(activity, intent);
    }

    public void onActivityResult(Activity ac, int requestCode, int resultCode, Intent data) {
        if (operation == null) {
            return;
        }
        operation.onActivityResult(ac, requestCode, resultCode, data);
    }

    public void onConfigurationChanged(Configuration newConfigs) {
        if (operation == null) {
            return;
        }
        operation.onConfigurationChanged(newConfigs);
    }

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

    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
        if (operation == null) {
            return;
        }
        operation.onWindowFocusChanged(activity, hasFocus);
    }
}
