package com.fq.channel.sdk.api;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import com.fq.channel.sdk.api.bean.LoginInfo;
import com.fq.channel.sdk.api.bean.PaymentInfo;
import com.fq.channel.sdk.base.Constants.AppConfig;
import com.fq.channel.sdk.base.Constants.FqConfig;
import com.fq.channel.sdk.base.Exception.BaseException;
import com.fq.channel.sdk.base.interfaces.PluginResult;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;
import com.fq.channel.sdk.base.net.FqNetRequest;
import com.fq.channel.sdk.base.net.HttpManager;
import com.fq.channel.sdk.base.net.callback.BaseCallback;
import com.fq.channel.sdk.base.net.req.ResultContent;
import com.fq.channel.sdk.base.net.req.ResultInitBody;
import com.fq.channel.sdk.base.utils.DeviceUtils;
import com.fq.channel.sdk.base.utils.FqLog;
import com.fq.channel.sdk.base.utils.Utils;
import com.fq.channel.sdk.core.JointManager;

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

import java.util.Map;

/**
 * @Description: 描述
 * @Author: FLuty
 * @CreateDate: 2020/4/3 15:59
 */
public class FqGameHander {

    private static final String TAG = "FqGameHander";

    //READ_PHONE_STATE 权限请求码
    public static final int REQUEST_CODE_READ_PHONE_STATE = 1;

    private static IResult<String> resultInit;

    public static void init(Activity activity, IResult<String> result) {
        resultInit = result;
        //初始化配置
        initSDKConfig(activity);
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            //如果没有读取权限的则进行权限的申请
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CODE_READ_PHONE_STATE);
        } else {
            //有权限的情况 直接读取imei并进行网络请求
            String imei = DeviceUtils.getIMEI();
            AppConfig.sImei = TextUtils.isEmpty(imei) ? "" : imei;
            initSDKNet();
        }
    }

    /**
     * 网络初始化
     */
    private static void initSDKNet() {
        FqNetRequest.init(new BaseCallback<ResultInitBody>() {
            @Override
            public void onFailure(BaseException msg) {
                FqLog.e(TAG, "initSDKNet onFailure :"+msg.getMsg());
                resultInit.onFail(msg.getMsg());
            }

            @Override
            public void onSuccess(int code, String msg, ResultInitBody data) {
                FqLog.i(TAG, "initSDKNet onSuccess :" + data.toString());
                initChannel(resultInit);
            }
        });
    }

    /**
     * sdk配置初始化
     */
    private static void initSDKConfig(Activity activity) {
        //初始化
        FqConfig fqConfig = FqConfig.get(activity);
        fqConfig.setCurrentActivity(activity);
        fqConfig.init(activity);
        HttpManager.getInstance().initHttp();
        JointManager.getInstance().initCfgConfigFile(activity);
    }

    /**
     * 渠道初始化
     */
    private static void initChannel(final IResult<String> resultInit) {
        JointManager.getInstance().init(FqConfig.get().getApplicationContext(), new PluginResultHandler() {
            @Override
            public void onHandlePluginResult(PluginResult result) {
                PluginResult.Status mStatus = result.getStatus();
                Log.i(TAG, "init mStatus :" + mStatus);
                if (PluginResult.Status.OK == mStatus) {
                    resultInit.onSuccess(result.getMessage());
                } else if (PluginResult.Status.CANCEL == mStatus) {
                    resultInit.onFail(result.getMessage());
                } else if (PluginResult.Status.ERROR == mStatus) {
                    resultInit.onFail(result.getMessage());
                }
            }
        });
    }

    public static void login(@NonNull Activity activity, final IResult<LoginInfo> resultLoginInfo) {
        JointManager.getInstance().login(activity, new PluginResultHandler() {
            @Override
            public void onHandlePluginResult(PluginResult result) {
                PluginResult.Status mStatus = result.getStatus();
                Log.i(TAG, "login mStatus :" + mStatus);

                if (PluginResult.Status.OK == mStatus) {
                    Object res_msg = result.getRawMessage();
                    JSONObject jo = (JSONObject) res_msg;
                    try {
                        resultLoginInfo.onSuccess(new LoginInfo(jo.get("uid").toString(), jo.get("token").toString()));
                    } catch (JSONException e) {
                        resultLoginInfo.onFail("JSONException");
                        e.printStackTrace();
                    }
                } else if (PluginResult.Status.CANCEL == mStatus) {
                    resultLoginInfo.onFail(result.getMessage());
                } else if (PluginResult.Status.ERROR == mStatus) {
                    resultLoginInfo.onFail(result.getMessage());
                }
            }
        });
    }

    public static void pay(@NonNull Activity activity, @NonNull final PaymentInfo paymentInfo, final IResult<String> resultPay) {
        try {
            Map map = Utils.getObjectToMap(paymentInfo);
            if (map == null){
                resultPay.onFail("params is null");
                return;
            }
            JointManager.getInstance().pay(activity, map, new PluginResultHandler() {
                @Override
                public void onHandlePluginResult(PluginResult result) {
                    PluginResult.Status mStatus = result.getStatus();
                    Log.i(TAG, "pay mStatus :" + mStatus);
                    if (PluginResult.Status.OK == mStatus) {
                        resultPay.onSuccess(result.getMessage());
                    } else if (PluginResult.Status.CANCEL == mStatus) {
                        resultPay.onFail(result.getMessage());
                    } else if (PluginResult.Status.ERROR == mStatus) {
                        resultPay.onFail(result.getMessage());
                    }
                }
            });
        } catch (IllegalAccessException e) {
            resultPay.onFail("params is null");
            e.printStackTrace();
        }
    }

    protected static void onRequestPermissionsResult(int requestCode,
                                                     String[] permissions, int[] grantResults) {
        if (REQUEST_CODE_READ_PHONE_STATE == requestCode
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //处理获取到读取IMEI权限的
            String imei = DeviceUtils.getIMEI();
            AppConfig.sImei = TextUtils.isEmpty(imei) ? "" : imei;
        } else {
            //获取不到读取IMEI权限
            AppConfig.sImei = "";
        }
        //无论是否获得IMEI读取权限都要进行初始化接口的调用
        initSDKNet();
    }

}
