package com.kfzs.duanduan.datashare;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.kfzs.duanduan.data.graph.provider.current.Current;
import com.kfzs.duanduan.data.graph.provider.player.User;
import com.kfzs.duanduan.datashare.provider.session.SessionBean;

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

import java.util.List;

/**
 * <pre>
 *     sinlov
 *
 *     /\__/\
 *    /`    '\
 *  ≈≈≈ 0  0 ≈≈≈ Hello world!
 *    \  --  /
 *   /        \
 *  /          \
 * |            |
 *  \  ||  ||  /
 *   \_oo__oo_/≡≡≡≡≡≡≡≡o
 *
 * </pre>
 * Created by sinlov on 17/3/5.
 */
public class KFZSDDCertificationDog implements ICertificationDog {

    public static final String TAG = "KFZSDog";
    private static KFZSDDCertificationDog instance;
    private Context context;
    private CertificationDog certificationDog;
    private String gamePN;
    private String gameCode;
    private String extrasString;
    private boolean isBundleOk = false;
    private static final String TAG_PACKAGE_RESPONSE_ACTIVITY = "com.kfzs.duanduan.data.observer.helper.WhistleActivity";
    private static final String EXTRAS_NEED_GET_TOKEN = "extras:act:game:certification:need:get:token:string";

    public static KFZSDDCertificationDog getInstance() {
        if (instance == null) {
            instance = new KFZSDDCertificationDog();
        }
        return instance;
    }

    @Override
    public void init(Context ctx, CertificationDog certificationDog) {
        this.context = ctx.getApplicationContext();
        if (this.context == null) {
            throw new NullPointerException("context is null!");
        }
        this.certificationDog = certificationDog;
        if (certificationDog == null) {
            throwCertificationDogNotInit();
        }
        checkConfig(ctx);
    }

    private void checkConfig(Context ctx) {
        String graphMeta;
        String dataShareMeta;
        try {
            ApplicationInfo info = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
            Bundle metaData = info.metaData;
            graphMeta = String.valueOf(metaData.get("DUANDUAN_GRAPH"));
            dataShareMeta = String.valueOf(metaData.get("DUANDUAN_DATASHARE"));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            graphMeta = "";
            dataShareMeta = "";
        }
        String graph = BuildConfigSaver.getInstance().getGraph();
        if (!graphMeta.equals(graph)) {
            throw new IllegalArgumentException("DUANDUAN_GRAPH in Manifest: " + graphMeta + " |in BuildConfig:  " + graph + " | not same, please check config");
        }
        String dataShare = BuildConfigSaver.getInstance().getDatashare();
        if (!dataShareMeta.equals(dataShare)) {
            throw new IllegalArgumentException("DUANDUAN_DATASHARE in Manifest: " + dataShareMeta + " |in BuildConfig:  " + dataShare + " | not same, please check config");
        }
    }

    @Override
    public void doForceNeedReLogin() {
        if (certificationDog != null) {
            certificationDog.onLoginJob();
        } else {
            throwCertificationDogNotInit();
        }
    }

    @Override
    public void doCertificationCode(Bundle extras) {
        if (extras != null) {
            try {
                checkBundle(extras);
            } catch (Exception e) {
                e.printStackTrace();
                certificationDog.onError(CertificationDog.RUNTIME_ERROR, "doCertificationCode runtime error, see log");
            }
        } else {
            throw new NullPointerException("Extras is null!");
        }
        if (certificationDog != null) {
            if (isBundleOk) {
                try {
                    if (extras.getBoolean(context.getString(R.string.kfzs_duanduan_datashare_certificationed))) {
                        Cursor player = DDProviderHelper.getInstance().getGameLastPalyer(context, gameCode);
                        if (player != null && player.getCount() > 0) {
                            player.moveToFirst();
                            String openId = player.getString(player.getColumnIndex(YogConfig.Game.LASTUSERID));
                            player.close();
                            if (!TextUtils.isEmpty(openId)) {
                                Cursor playerInfo = DDProviderHelper.getInstance().getPlayer(context, openId, gameCode);
                                if (playerInfo != null && playerInfo.getCount() > 0) {
                                    playerInfo.moveToFirst();
                                    String token = playerInfo.getString(playerInfo.getColumnIndex(YogConfig.Player.TOKEN));
                                    String openID = playerInfo.getString(playerInfo.getColumnIndex(YogConfig.Player.OPENID));
                                    User user = new User();
                                    user.setMToken(token);
                                    user.setMOpenId(openID);
                                    certificationDog.onCertificationCodeCallBack(user, gamePN, gameCode, extrasString);
                                }
                                if (playerInfo != null)
                                    playerInfo.close();
                            } else {
                                player.close();
                                certificationDog.onLoginJob();
                            }
                        } else {
                            if (player != null)
                                player.close();

                            List<User> userList = DDProviderHelper.getInstance().getUserList(context);
                            if (null != userList && userList.size() > 0) {
                                User userNew = userList.get(userList.size() - 1);
                                User user = new User();
                                user.setMToken(userNew.getMToken());
                                user.setMOpenId(userNew.getMOpenId());
                                certificationDog.onCertificationCodeCallBack(user, gamePN, gameCode, extrasString);
                            } else
                                certificationDog.onLoginJob();
                        }
                        //                        certificationDog.onCertificationCodeCallBack(outHeadSession, gamePN, gameCode, extrasString);
                    } else {
                        if (isChangeAccout()) {//切换帐号
                            String token = extras.getString(EXTRAS_NEED_GET_TOKEN);
                            User user = new User();
                            if (!TextUtils.isEmpty(token)) {
                                user.setMToken(token);
                            }
                            certificationDog.onCertificationCodeCallBack(user, gamePN, gameCode, extrasString);
                        } else if (checkLogin()) {
                            //                            SessionBean outHeadSession = KFZSDDContentSession.getInstance().findOutHeadSession(context);
                            Current lastUser = DDProviderHelper.getInstance().getLastUser(context);
                            certificationDog.onCertificationCodeCallBack(new User(lastUser), gamePN, gameCode, extrasString);
                        } else {
                            certificationDog.onLoginJob();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    certificationDog.onError(CertificationDog.RUNTIME_ERROR, "doCertificationCode runtime error, see log");
                }
            } else {
                certificationDog.onError(CertificationDog.BUNDLE_ERROR, "bundle error");
            }
        } else {
            throwCertificationDogNotInit();
        }
    }


    @Override
    public void doCertification(String certificationCode, String extras) {
        if (certificationDog != null) {
            if (!TextUtils.isEmpty(certificationCode)) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName(gamePN, TAG_PACKAGE_RESPONSE_ACTIVITY);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_key), certificationCode);

                    if (TextUtils.isEmpty(extras)) {
                        intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_package_extras), "");
                        Log.w(TAG, "warning extras is empty!");
                    } else {
                        intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_package_extras), extras);
                    }
                    context.startActivity(intent);
                    certificationDog.onCertificationSuccess();
                } catch (Exception e) {
                    e.printStackTrace();
                    certificationDog.onError(CertificationDog.TARGET_APP_CAN_NOT_FIND, "target app can not start!");
                }
            } else {
                certificationDog.onError(CertificationDog.CERTIFICATION_CODE_NOT_HAVE, "certification code is empty");
            }
        } else {
            throwCertificationDogNotInit();
        }
    }

    @Override
    public void doCertificationCancel() {
        if (certificationDog != null) {
            if (TextUtils.isEmpty(gamePN)) {
                new IllegalArgumentException("you are not use doCertificationCode()!").printStackTrace();
                certificationDog.onError(CertificationDog.RUNTIME_ERROR, "doCertificationCancel runtime error, see log");
            }
            try {
                Intent intent = new Intent();
                intent.setClassName(gamePN, TAG_PACKAGE_RESPONSE_ACTIVITY);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(context.getString(R.string.kfzs_duanduan_datashare_certification_cancel), "cancel");
                context.startActivity(intent);
                certificationDog.onCertificationCancel();
            } catch (Exception e) {
                e.printStackTrace();
                certificationDog.onError(CertificationDog.TARGET_APP_CAN_NOT_FIND, "target app can not start!");
            }
        } else {
            throwCertificationDogNotInit();
        }
    }

    private void checkBundle(Bundle extras) {
        String gamePN = extras.getString(context.getString(R.string.kfzs_duanduan_datashare_package_name), "");
        String gameCode = extras.getString(context.getString(R.string.kfzs_duanduan_datashare_game_code), "");
        String extrasString = extras.getString(context.getString(R.string.kfzs_duanduan_datashare_package_extras), "");
        if (TextUtils.isEmpty(gamePN) || TextUtils.isEmpty(gameCode)) {
            String msg = "need Certification APK can not send bundle by right key! like game package name or game code";
            if (certificationDog != null) {
                certificationDog.onError(CertificationDog.PARAMS_ERROR, msg);
            } else {
                Log.w(TAG, msg);
            }
        } else {
            this.isBundleOk = true;
            this.gamePN = gamePN;
            this.gameCode = gameCode;
            this.extrasString = extrasString;
        }
    }

    private boolean checkLogin() {
        Current lastUser = DDProviderHelper.getInstance().getLastUser(context);
        return lastUser != null;
    }

    private boolean isChangeAccout() {
        try {
            if (!TextUtils.isEmpty(extrasString)) {
                JSONObject object = new JSONObject(extrasString);
                String userBehavior = object.getString("user_behavior");
                if (TextUtils.equals(userBehavior, "change_account")) {
                    return true;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        if (certificationDog != null) {

        } else {
            throwCertificationDogNotInit();
        }
    }

    private void throwCertificationDogNotInit() {
        throw new NullPointerException("certificationDog is null, you can get any call from dog!");
    }

    private KFZSDDCertificationDog() {
    }
}
