package cn.yyxx.commsdk.core.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import cn.yyxx.commsdk.base.entity.ResultInfo;
import cn.yyxx.commsdk.base.internal.ICallback;
import cn.yyxx.commsdk.base.internal.IRequestCallback;
import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.commsdk.core.SdkDrive;
import cn.yyxx.commsdk.core.constants.Constants;
import cn.yyxx.commsdk.core.network.SdkRequest;
import cn.yyxx.commsdk.core.ui.dialog.PrivacyPolicyDialog;
import cn.yyxx.commsdk.core.ui.dialog.SingleButtonDialog;
import cn.yyxx.commsdk.core.utils.ManifestUtils;
import cn.yyxx.commsdk.core.utils.ParamsUtils;
import cn.yyxx.commsdk.core.utils.ResourceUtil;
import cn.yyxx.commsdk.core.utils.SharedPreferencesUtils;
import cn.yyxx.commsdk.impl.channel.msa.IMsaDeviceIdsCallback;
import cn.yyxx.commsdk.impl.channel.msa.MsaDeviceIdsHandler;
import cn.yyxx.support.JsonUtils;

import cn.yyxx.support.permission.IPermissionCallback;
import cn.yyxx.support.permission.Permission;
import cn.yyxx.support.permission.PermissionKit;

public class CommonOperationManager {
    public static CommonOperationManager permissionManager = null;

    private boolean hasIdsRead = false;


    private CommonOperationManager(){}
    public static CommonOperationManager getInstance(){
        if (permissionManager == null){
            permissionManager = new CommonOperationManager();
        }
        return permissionManager;
    }
    public void initAgreement(Activity activity, ICallback callback){

        if (TextUtils.isEmpty(ParamsUtils.getGameCode(activity))){
            new SingleButtonDialog.Builder(activity)
                    .setPositiveButton(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            System.exit(0);
                        }
                    })
                    .Create(activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_params_error_tip")))
                    .show();
            return;
        }


        String isShowPolicy = SharedPreferencesUtils.getSharedPreferences(activity, Constants.SP_KEY,"isShowPolicy");

        if (isShowPolicy.isEmpty()){
            SdkRequest.getInstance().initAgreement(activity, new IRequestCallback() {
                @Override
                public void onResponse(ResultInfo resultInfo) {


                    if (resultInfo.code == 400){
                        new SingleButtonDialog.Builder(activity)
                           .setPositiveButton(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                System.exit(0);
                            }
                        })
                           .Create(activity.getString(ResourceUtil.getStringId(activity,"yyxx_comm_network_error_tip")))
                           .show();
                        return;
                    }
                    String policy_url = "";

                    try {
                        if (JsonUtils.hasJsonKey(new JSONObject(resultInfo.data),"agreement_url")){

                            JSONObject jsonObject = new JSONObject(resultInfo.data);
                            policy_url = jsonObject.getString("agreement_url");

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (policy_url.isEmpty()){
                        requestPermission(activity,callback);
                        return;
                    }

                    new PrivacyPolicyDialog(activity, policy_url, new PrivacyPolicyDialog.OnClosePageListener() {
                        @Override
                        public void onUserAgreePolicy() {
                            SharedPreferencesUtils.setSharedPreferences( Constants.SP_KEY,"isShowPolicy","1",activity);
                            requestPermission(activity,callback);
                        }

                        @Override
                        public void onUserDisagreePolicy() {
                            callback.onResult(Constants.CODE_FAIL,"User disagree policy");
                        }
                    }).show();
                }
            });

        }else{
            requestPermission(activity,callback);
        }

    }

    public void initialize(Activity activity, Boolean isLandscape, ICallback callback){
        SdkRequest.getInstance().initSdk(activity, new IRequestCallback() {
            @Override
            public void onResponse(ResultInfo resultInfo) {
                    Logger.d(resultInfo.msg);
            }
        });
    }


    public void initMsaDeviceIds(Application application,Context context){
        MsaDeviceIdsHandler.initMsaDeviceIds(application, new IMsaDeviceIdsCallback() {
            @Override
            public void onIdsRead(int code, String msg, Map<String, String> ids) {

            }
        });
    }
    @SuppressLint("MissingPermission")
    public JSONObject getIfa(Context context){
        String ifa = "";
        String ifa_type= "";

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){

                ifa = MsaDeviceIdsHandler.oaid;
                ifa_type =  "2";
        }else{
            if (PermissionKit.isGranted(context,Permission.READ_PHONE_STATE)){
                @SuppressLint("ServiceCast") TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELECOM_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    ifa = telephonyManager.getImei();
                }else{
                    ifa = telephonyManager.getDeviceId();
                }
            }
            ifa_type = "1";
        }

        if (ifa.isEmpty()){
            ifa = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            ifa_type = "3";
            if (ifa.isEmpty()){
                ifa = userSimulateImei(context);
                ifa_type = "0";
            }
        }

        JSONObject json = new JSONObject();
        try {
            json.put("ifa",ifa);
            json.put("ifa_type",ifa_type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }


    static String userSimulateImei(Context context){

        String  simulateImei  = SharedPreferencesUtils.getSharedPreferences(context,Constants.SP_KEY, "simulateImei");

        if (!simulateImei.isEmpty()){
            return simulateImei;
        }else {

            // 用putString的方法保存数据
            String encryptMD5to16 ="YYR" + simulateUniqueId().substring(8, 24);

            SharedPreferencesUtils.setSharedPreferences(Constants.SP_KEY,"simulateImei",encryptMD5to16,context);


            return encryptMD5to16;
        }
    }



    //获得独一无二的Psuedo ID
    public static String simulateUniqueId() {
        String serial = null;

        String m_szDevIDShort = "" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        String  time = m_szDevIDShort + (System.currentTimeMillis());
        return  getMD5(time);
    }

    public static String getMD5(String content) {
        String s = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(content.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }


    void requestPermission(Activity activity,ICallback callback){

        if (!ManifestUtils.getMetaDataValue(activity,"yyxx.SkipPermission").isEmpty()){
            callback.onResult(Constants.CODE_SUCCESS,"User agree policy");
        }else if (!SharedPreferencesUtils.getSharedPreferences(activity,Constants.SP_KEY,"yyxxStopRequestPermission").isEmpty()){
            callback.onResult(Constants.CODE_SUCCESS,"User agree policy");
        }else{
            goRequestPermission(activity, new PermissonCallBack() {
                @Override
                public void onResult(Result code) {
                    if (code == Result.FINISH){
                        SdkDrive.getInstance().initDrive(activity);
                        callback.onResult(Constants.CODE_SUCCESS,"User agree policy");
                    }
                }
            });
        }

    }


    void goRequestPermission(Activity activity,PermissonCallBack permissonCallBack) {

        PermissionKit.enablePermissionDialog = false;
        PermissionKit.with()
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.Group.STORAGE)
                .request(activity, new IPermissionCallback() {
                    @Override
                    public void onGranted(List<String> list, boolean all) {
                        permissonCallBack.onResult(Result.GRANT);
                    }

                    @Override
                    public void onDenied(List<String> list, boolean never) {
                        permissonCallBack.onResult(Result.DENIED);
                    }

                    @Override
                    public void onProxyFinish() {

                        permissonCallBack.onResult(Result.FINISH);


                    }
                });
    }



    public interface PermissonCallBack{
        void onResult(Result code);
    }



    public enum Result{
        /**
         * 授权
         */
        GRANT,
        /**
         * 拒绝
         */
        DENIED,
        /**
         * 跳过
         */
        SKIP,
        /**
         * 首次拒绝，第二次不再申请
         */
        STOP,
        FINISH
    }
}
