package com.yyrh.sdk.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.yyrh.entity.ResultInfo;
import com.yyrh.internal.IRequestCallback;
import com.yyrh.network.SdkRequest;
import com.yyrh.sdk.SdkCallback;
import com.yyrh.sdk.callback.InitCallback;
import com.yyrh.utils.YYLog;
import com.yythird.sdk.ChannelSDK;

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

import cn.yyxx.support.device.DeviceInfoUtils;

/**
 * @author #Suyghur.
 * Created on 2021/10/18
 */
public class SDKEntryImpl {

    private InitCallback initCallback = null;

    private static boolean hasReadIds = false;
    private static String deviceIds = "";

    private volatile AtomicInteger timeCount = new AtomicInteger(0);

    private SdkCallback mSdkCallback = 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, "");
            }
            SdkNativeBoost.getInstance().setParam("ifa", oaid);
            hasReadIds = true;
            YYLog.d("device ids initialize finish...");
        }

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

        @Override
        public void onShowGameExit() {

        }
    };

    public SDKEntryImpl(Context context) {
        // 初始化配置
    }

    public void initSdk(final Activity activity, final InitCallback callback, boolean isDebug) {
        // 初始化设备参数
        this.initCallback = callback;
        ChannelSDK.getInstance().SDKInit(activity, mSdkCallback);
        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);
        }
    }

    public void initDeviceInfo(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            SdkNativeBoost.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);
                SdkNativeBoost.getInstance().setParam("ifa_type", "3");
            } else {
                // 如果授权了
                ids = DeviceInfoUtils.getImei(activity);
                SdkNativeBoost.getInstance().setParam("ifa_type", "1");
            }
            mSdkCallback.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) {
                    // 初始化成功
                    callback.onInitSuccess("sdk初始化成功");
                } else {
                    if (TextUtils.isEmpty(resultInfo.msg)) {
                        callback.onInitFailed("sdk初始化失败");
                    } else {
                        callback.onInitFailed(resultInfo.msg);
                    }
                }
            }
        });
    }
}
