package com.excelliance.open;

import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.excelliance.lbui.R;
import com.excelliance.open.dialog.LoadingDialog;
import com.excelliance.open.floatwindow.RecordFloatWindow;

import com.excelliance.open.floatwindow.ProgressFloatWindow;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;


public class BwbxUI {
    private Context mContext;
    private boolean sIsGamePlugin;

    private static final String TAG = "BwbxUI";

    private CustomDialog exitDialog = null;
    private CustomDialog gameDialog = null;
    private CustomDialog userDialog = null;
    private Dialog progressDialog = null;
    private CustomDialog switchFull = null;
    private CustomDialog downloadFull = null;
    private CustomDialog downloadMissing = null;
    private CustomDialog downloadAll = null;
    private CustomDialog downloadAllLater = null;
    private CustomDialog downloadAllLaterInterface = null;
    private CustomDialog downloadFullRes = null;
    private CustomDialog remainingResDowning = null;

    private String lebian_download_all_note = null;
    private String lebian_download_all_note_al = null;
    private String lebian_download_all_note_interface = null;
    private String lebian_download_full_res = null;
    private String lebian_download_full_res_without_wifi = null;
    private String lebian_download_all_note_switch_gnet = null;
    private String lebian_err_loadres_generic = null;
    private String lebian_err_loadres_network = null;
    private String lebian_err_loadres_timeout = null;
    private String lebian_err_loadres_outofspace = null;
    private String lebian_err_loadres_md5_mis = null;
    private String lebian_err_loadres_rename_fail = null;
    private String lebian_choose_by_user_bwbx = null;
    private String lebian_network_environment_poor = null;
    private String lebian_remaining_res_downloading = null;
    private int gameDialogType = 0;
    private TextView textProgress = null;
    private RecordFloatWindow rfw;
    private ProgressFloatWindow pfw;
    private boolean bwbxIsFinished = false;
    private boolean canShowFloatWinLater = false;
    private Activity mActivity;
    private long mRemainSize = 0;
    private AtomicBoolean showing = new AtomicBoolean(false);
    private boolean firstTimeReceive = true;
    private boolean mFloatWinIsShowing = false;//出现过了，就不再消失

    public BwbxUI(Context context) {
        mContext = context;
    }

    public void init(Application app, boolean isRecode) {
        Log.d(TAG, "init isrecord:"+isRecode);
        IntentFilter filter = new IntentFilter();
        filter.addAction(getPackageName()+getString(mContext, "ACTION_QUERY_USER", ""));
        filter.addAction(getPackageName()+getString(mContext, "ACTION_QUERY_RETRY", ""));
        filter.addAction(getPackageName()+getString(mContext, "ACTION_FINISHED", ""));
        filter.addAction(getPackageName()+getString(mContext, "ACTION_DOWNLOAD_MISSING_PROGRESS", ""));
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction("com.excelliance.open.action.downloadProportionInfo");
        filter.addAction(getPackageName()+getString(mContext, "ACTION_RECORD_SIZE", ""));
        LBContextCompat.registerReceiver(mContext,bwbxbr,filter);
        boolean success = PreferencesHelper.getBoolean(mContext, PreferencesHelper.MODULE_DLOADINFO, "success", false);
        boolean showFloat = getGlobalBoolean(mContext, "SHOW_BWBX_FLOAT_WINDOW", false);
        if (showFloat && !isRecode && !success) {
            canShowFloatWinLater = isWifi(mContext);
            registerFloatWindow(app,isRecode);
        }
        if (isRecode) {
            registerFloatWindow(app,isRecode);
        }
    }

    private BroadcastReceiver bwbxbr = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "action="+action);
            if (action.equals("com.excelliance.open.action.downloadProportionInfo")) {
                int proportion = intent.getIntExtra("proportion", 0);
                long size = intent.getLongExtra("size", 0);
                if (pfw != null) {
                    mRemainSize = size;
                    pfw.setProgress(proportion);
                    pfw.setRemainSize(size);
                    if (proportion == 100){
                        pfw.setRemainSize(0);
                        pfw.dismiss();
                        pfw = null;
                    }
                }
                if (proportion == 100){
                    bwbxIsFinished = true;
                }
                return;
            }
            if (action.equals(getPackageName() + getString(mContext, "ACTION_RECORD_SIZE", ""))) {
                if (rfw != null) {
                    long size = intent.getLongExtra("size", 0);
                    int count = intent.getIntExtra("count", 0);
                    Log.d(TAG, "size = "+size+" count:"+count);
                    rfw.setPkgSize(count, size);
                }
                return;
            }
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                if (firstTimeReceive) // network change received immediately after broadcast registered, so we skip for the first time
                    firstTimeReceive = false;
                else {
                    //获得ConnectivityManager对象
                    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

                    //获取ConnectivityManager对象对应的NetworkInfo对象
                    //获取WIFI连接的信息
                    NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    //获取移动数据连接的信息
                    NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                    if (wifiNetworkInfo != null && dataNetworkInfo != null) {
                        Log.d(TAG, "wifi state:"+wifiNetworkInfo.isConnected()+ " data stat:"+dataNetworkInfo.isConnected());
                        if (!wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()){
                            Log.d(TAG, "wifiState  =WIFI已断开,移动数据已连接");
                            if (!bwbxIsFinished && canShowFloatWinLater) {
                                if (mActivity != null){
                                    if (pfw == null) {
                                        pfw = new ProgressFloatWindow(mContext, mActivity);
                                    }
                                    pfw.setRemainSize(mRemainSize);
                                    pfw.show();

                                }
                                canShowFloatWinLater = false;

                            }
                        }
                    }
                }
                return;
            }

            int receiveType = intent.getIntExtra("type", 0);
            Log.d(TAG, " receiveType="+receiveType);
            if ((!action.equals(getPackageName() + getString(mContext, "ACTION_QUERY_USER", "")) || (receiveType != getInt(mContext, "ACTION_TYPE_PRELOAD_DIALOG", 0)))) {
                if ((!isForeground(mContext) || showing.get() || isLBMainOnTop(context))) {
                    Log.d(TAG, "has dialog");
                    dialogRejected(mContext, receiveType);
                    return;
                }
            }

            if (!action.equals(getPackageName() + getString(mContext, "ACTION_DOWNLOAD_MISSING_PROGRESS", "")) && (!action.equals(getPackageName() + getString(mContext, "ACTION_QUERY_USER", "")) || receiveType != getInt(mContext, "ACTION_TYPE_PROGRESS", 0))) { //如果不是进度广播或者不是动画广播就把动画隐藏掉
                if (progressDialog != null && progressDialog.isShowing()) {
                    Log.d(TAG, "dismiss progress");
                    dialogRejected(mContext, getInt(mContext, "ACTION_TYPE_PROGRESS", 0));
                    showProgressDialog(-1, true);
                }
            }

            if (action.equals(getPackageName()+getString(mContext, "ACTION_QUERY_RETRY", ""))) {
                showGameDialog(intent, true);
                //platDo(getInt(mContext, "ACTION_TYPE_CHECK_FOREGROUND", 0));
            }
            else if (action.equals(getPackageName()+getString(mContext, "ACTION_QUERY_USER", ""))) {
                int type = intent.getIntExtra("type", 0);
                Log.d(TAG, "acti="+action+", type="+type);
                if(type == getInt(mContext, "ACTION_TYPE_QUERY", 0)){
                    int size = intent.getIntExtra(getString(mContext, "ACTION_SIZE", ""), 0);
                    showUserDialog(size);
                    //platDo(getInt(mContext, "ACTION_TYPE_CHECK_FOREGROUND", 0));
                }else if(type == getInt(mContext, "ACTION_TYPE_PROGRESS", 0)){
                    //show downloading progress bar
                    if(getGlobalBoolean(mContext, "SHOW_LOADING_PROGRESS_BWBX", true)){
                        int progress = intent.getIntExtra("progress", -1);
                        showProgressDialog(progress, true);
                    }
                }
                else if (type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_FULL", 0)) {
                    Log.d(TAG, "ACTION_TYPE_DOWNLOAD_FULL");
                    showDownloadFull(true);
                }
                else if (type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_MISSING", 0)) {
                    Log.d(TAG, "ACTION_TYPE_DOWNLOAD_MISSING");
                    showDownloadMissing(true);
                }
                else if (type == getInt(mContext, "ACTION_TYPE_SWITCH_FULL", 0)) {
                    showSwitchFull(true);
                }
                else if(type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_ALL_WITHOUT_WIFI", 0)) {
                    long size = intent.getLongExtra(getString(mContext, "ACTION_SIZE", ""), 0);
                    Log.d(TAG, "size:" + size);
                    showDownloadAll(size, true);
                }
                else if(type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_ALL_WITHOUT_WIFI_LATER", 0)) {
                    long size = intent.getLongExtra("size", 0);
                    boolean zipExists = intent.getBooleanExtra("zipExists", false);
                    boolean dataConnection = intent.getBooleanExtra("dataConnection", false);
                    boolean downloadZip = intent.getBooleanExtra("downloadZip", false);
                    Log.d(TAG, "size:" + size + " zipExists:"+zipExists+" downloadZip:"+downloadZip+" dataConnection:"+dataConnection);
                    showDownloadAllLater(size, zipExists, downloadZip, dataConnection, true);
                }
                else if(type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_ALL_WITHOUT_WIFI_LATER_INTERFACE", 0)) {
                    long size = intent.getLongExtra("size", 0);
                    boolean zipExists = intent.getBooleanExtra("zipExists", false);
                    boolean dataConnection = intent.getBooleanExtra("dataConnection", false);
                    boolean downloadZip = intent.getBooleanExtra("downloadZip", false);
                    Log.d(TAG, "size:" + size + " zipExists:"+zipExists+" downloadZip:"+downloadZip+" dataConnection:"+dataConnection);
                    showDownloadAllLaterInterface(size, zipExists, downloadZip, dataConnection, true);
                }
                else if(type == getInt(mContext, "ACTION_TYPE_REMAINGING_RES_DOWNLOADING", 0)) {
                    long size = intent.getLongExtra("size", 0);
                    Log.d(TAG, "size:" + size);
                    showRemainingResDownloading(size, true);
                }
                else if(type == getInt(mContext, "ACTION_TYPE_DOWNLOAD_ALL_RES", 0)) {
                    long size = intent.getLongExtra(getString(mContext, "ACTION_SIZE", ""), 0);
                    int triggerReason = intent.getIntExtra("triggerReason", 0);

                    int zipType = intent.getIntExtra("zipType", 1);
                    Boolean needOneButton = intent.getBooleanExtra("needOneButton", false);
                    Log.d(TAG, "size:" + size + " triggerReason:"+triggerReason + " zipType:"+zipType+" needOneButton:"+needOneButton+" extra:"+intent.getExtras());
                    showDownloadFullRes(size, zipType, true, triggerReason, needOneButton,intent.getExtras());
                }
                else if(type == getInt(mContext, "ACTION_TYPE_PRELOAD_DIALOG", 0)) {
                    showDownloadAllLater(0L, false, false, false, false);
                    showDownloadAllLaterInterface(0L, false, false, false, false);
                    showRemainingResDownloading(0L, false);
                    showSwitchFull(false);
                    showGameDialog(intent, false);
                    showProgressDialog(1, false);
                    showDownloadFull(false);
                    showDownloadMissing(false);
                    showDownloadAll(0L, false);
                    showDownloadFullRes(0L, false);
                }
            }
            else if (action.equals(getPackageName()+getString(mContext, "ACTION_DOWNLOAD_MISSING_PROGRESS", ""))) {
                if (textProgress != null && progressDialog != null && progressDialog.isShowing()){
                    final int downloaded = intent.getIntExtra("downloaded", 0);
                    String loading = getResources(mContext).getString(R.string.lebian_progress_loading);
                    textProgress.setText(String.format("%s%d%%", loading, downloaded));
                }
            }
            /*
			else if (action.equals(getPackageName()+getString(mContext, "ACTION_FINISHED", ""))) {
				String libName = intent.getStringExtra("gamelib");
				if (getPackageName().equals(libName)) {
					BwbxUtil.setFull(intent.getStringExtra("version"), intent.getStringExtra("savePath"));
				}
			}
			*/
        }
    };

    private void platDo(int type) {
        Log.d(TAG, "platDo type="+type);
        Intent intent = new Intent(getString(mContext, "ACTION_PLAT_DO", ""));
        intent.setPackage(getPackageName());
        intent.setComponent(new ComponentName(mContext, getClassName(mContext, "main.BGService")));
        intent.putExtra(getString(mContext, "ACTION_TYPE", ""), type);
        startService(intent, mContext);
    }

    private void showSwitchFull(final boolean show) {
        Log.d(TAG, "showSwitchFull ENTER");

        if (switchFull == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showSwitchFull no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            builder.setMessage(res.getString(R.string.lebian_switch_to_full));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent nextIntent = new Intent("com.excelliance.open.NEXT_CHAPTER");
                    nextIntent.setPackage(getPackageName());
                    nextIntent.setComponent(new ComponentName(mContext, getClassName(mContext, "main.BGService")));
                    startService(nextIntent,mContext);
                    dismiss(dialog);
                    switchFull = null;
                }
            });

            builder.setNegativeButton(res.getString(R.string.lebian_button_cancel), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    switchFull = null;
                }
            });

            switchFull = builder.create();
            switchFull.setCancelable(false);
            switchFull.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }
        if(!switchFull.isShowing() && show) {
            show(switchFull);
        }

    }

    private void showGameDialog(Intent intent, final boolean show) {
        Log.d(TAG, "showGameDialog ENTER");

        if (gameDialog == null || !show) {
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showGameDialog no topActivity");
                return;
            }
            Resources res = getResources(mContext);
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            final Context sInstance = mContext;
            final String packageName = sInstance.getPackageName();

            lebian_err_loadres_generic = res.getString(R.string.lebian_err_loadres_generic);
            lebian_err_loadres_network = res.getString(R.string.lebian_err_loadres_network);
            lebian_err_loadres_timeout = res.getString(R.string.lebian_err_loadres_timeout);
            lebian_err_loadres_outofspace = res.getString(R.string.lebian_err_loadres_outofspace);
            lebian_err_loadres_md5_mis = res.getString(R.string.lebian_err_loadres_md5_mis);
            lebian_err_loadres_rename_fail = res.getString(R.string.lebian_err_loadres_rename_fail);
            builder.setMessage(res.getString(R.string.lebian_err_loadres_generic));
            builder.setTitle(res.getString(R.string.lebian_hint));
            //int retryId = res.getIdentifier("button_ok", "string", packageName);
            builder.setPositiveButton(res.getString(R.string.lebian_retry), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    userRetry(mContext);
                    dismiss(dialog);
                    gameDialog = null;
                    userClick(mContext, gameDialogType, 1);
                }
            });

            if (getGlobalBoolean(mContext, "ENABLE_EXIT_BUTTON", false)) {
                builder.setNegativeButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss(dialog);
                        finishActivitys(mContext);
                        platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                        platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                        gameDialog = null;
                        //android.os.Process.sendSignal(android.os.Process.myPid(), 1000);
                        userClick(mContext, gameDialogType, 2);
                    }
                });
            }

            gameDialog = builder.create();
            gameDialog.setCancelable(false);
            gameDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
                {
                    if (keyCode == KeyEvent.KEYCODE_SEARCH)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            });
        }

        if (!gameDialog.isShowing() && show) {
            long errcode = intent.getLongExtra("errcode", -1);
            String exception = intent.getStringExtra("exceptionInfo");
            String desc = lebian_err_loadres_generic;
            int type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_UNKNOWN", 0);
            if (errcode == getInt(mContext, "ERR_NETWORK", 0)) {
                desc = lebian_err_loadres_network;
                type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_ERR_NETWORK", 0);
            }
            else if (errcode == getInt(mContext, "ERR_TIMEOUT", 0)){
                desc = lebian_err_loadres_timeout;
                type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_TIMOUT", 0);
            }
            else if (errcode == getInt(mContext, "ERR_SPACE_NOT_ENOUGH", 0)){
                desc = lebian_err_loadres_outofspace;
                type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_SPACE_NOT_ENOUGH", 0);
            }
            else if (errcode == getInt(mContext, "ERR_MD5_MIS", 0)){
                desc = lebian_err_loadres_md5_mis;
                type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_MD5_MIS", 0);
            }
            else if (errcode == getInt(mContext, "ERR_RENAME_FAIL", 0)){
                desc = lebian_err_loadres_rename_fail;
                type = getInt(mContext, "DIALOG_TYPE_DOWNLOAD_FAILED_RENAME_FAIL", 0);
            }
            gameDialogType = type;
            String msg = (errcode == -1 && exception != null && exception.length()>0) ? (desc+"("+exception+")") : desc;
            gameDialog.setMessage(msg);
            show(gameDialog);
        }
    }

    private void showUserDialog(int size) {
        Log.d(TAG, "showUserDialog ENTER");

        if (userDialog == null) {
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showUserDialog no topActivity");
                return;
            }
            Resources res = getResources(mContext);
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            final Context sInstance = mContext;
            int resId = R.string.lebian_download_note;
            int resIdPos = 0;
            int resIdNeg = 0;
            String sizeStr = "";
            int sizeM = size/(1024*1024);
            int sizeK = size/1024;
            if(sizeM > 0){
                sizeStr += (sizeM+"."+((size%(1024*1024))/103))+"MB";
            }else{
                if(size%1024 != 0){
                    sizeK++;
                }
                sizeStr += (sizeK)+"KB";
            }
            final int dialogType;
            final String packageName = sInstance.getPackageName();
            boolean packageReady = false;
            boolean patchDownloaded = false;
            try {
                Class versionManager = Class.forName("com.excelliance.open.VersionManager");
                Method getInstance = versionManager.getDeclaredMethod("getInstance", new Class[] {});
                getInstance.setAccessible(true);
                Object vm = getInstance.invoke(null, new Object[] {});
                Method setContext = versionManager.getDeclaredMethod("setContext", Context.class);
                setContext.setAccessible(true);
                setContext.invoke(vm, mContext);

                Method pkgReady = versionManager.getDeclaredMethod("packageReady", new Class[] {});
                pkgReady.setAccessible(true);
                Boolean result = (Boolean)pkgReady.invoke(vm, new Object[] {});
                packageReady = result.booleanValue();

                Method patchDled = versionManager.getDeclaredMethod("patchDownloaded", new Class[] {});
                patchDled.setAccessible(true);
                result = (Boolean)patchDled.invoke(vm, new Object[] {});
                patchDownloaded = result.booleanValue();
            }
            catch (Exception e) {
                Log.d(TAG, "no versionManager");
                e.printStackTrace();
            }
            Log.d(TAG, "packageReady:"+packageReady+" patchDownloaded"+patchDownloaded);
            if (packageReady) {
                // if the whole package is ready for use, or whole patch downloaded, switch to the whole package
                resId = R.string.lebian_restart_required;
                dialogType = 1;
                resIdPos = R.string.lebian_button_ok;
            }else if(patchDownloaded){
                dialogType = 2;
                resId = R.string.lebian_err_loadres_outofspace;
                resIdPos = R.string.lebian_clean_now;
            }else{
                dialogType = 0;
                resId = R.string.lebian_download_missing_note;
                resIdPos = R.string.lebian_continue_game;
                resIdNeg = R.string.lebian_enable_now;
            }
            builder.setMessage(res.getString(resId));
            builder.setTitle(res.getString(R.string.lebian_hint));
            if(resIdPos > 0){
                builder.setPositiveButton(res.getString(resIdPos), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss(dialog);
                        platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                        if(dialogType == 1){
                            Intent intent = new Intent("com.excelliance.open.NEXT_CHAPTER");
                            intent.setPackage(getPackageName());
                            intent.setComponent(new ComponentName(mContext, getClassName(mContext, "main.BGService")));
                            startService(intent,sInstance);
                        }else if(dialogType == 2){
                            finishActivitys(mContext);
                            platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                        }
                        userAction(mContext, 1, 1);
                        userDialog = null;
                    }
                });
            }
            if(resIdNeg > 0){
                builder.setNegativeButton(res.getString(resIdNeg), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss(dialog);
                        finishActivitys(mContext);
                        platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                        userAction(mContext, 1, 2);
                        platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                        userDialog = null;
                    }
                });
            }

            userDialog = builder.create();
            userDialog.setCancelable(false);
            userDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_BACK:
                        case KeyEvent.KEYCODE_SEARCH:{
                            return true;
                        }

                        default:
                            return false;
                    }
                }
            });
        }

        if(!userDialog.isShowing()) {
            show(userDialog);
        }

    }

    private void showProgressDialog(int progress, final boolean show) {
        Log.d(TAG, "showProgressDialog ENTER, progress="+progress);

        if(progress == -1){
            hideProgress(progressDialog);
            return;
        }

        if (progressDialog == null || !show) {

            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showProgressDialog no topActivity");
                return;
            }
            LoadingDialog.Builder builder = new LoadingDialog.Builder(mContext, getTopActivity(mContext));
            builder.setProgress(res.getString(R.string.lebian_progress_loading));
            progressDialog = builder.create();
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_BACK:
                        case KeyEvent.KEYCODE_SEARCH:{
                            return true;
                        }

                        default:
                            return false;
                    }
                }
            });
        }

        if (!progressDialog.isShowing() && show) {
            progressDialog.show();
        }

        if(progress >= 100){
            progressDialog.dismiss();
            progressDialog = null;
        }

    }

    private void showDownloadFull(final boolean show) {
        Log.d(TAG, "showDownloadFull ENTER");

        if (downloadFull == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadFull no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            builder.setMessage(res.getString(R.string.lebian_resource_missing));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_download_now), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent nextIntent = new Intent("com.excelliance.open.NEXT_CHAPTER");
                    nextIntent.setPackage(getPackageName());
                    nextIntent.setComponent(new ComponentName(mContext, getClassName(mContext, "main.BGService")));
                    startService(nextIntent, mContext);
                    dismiss(dialog);
                    downloadFull = null;
                }
            });

            downloadFull = builder.create();
            downloadFull.setCancelable(false);
            downloadFull.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }

        if(!downloadFull.isShowing() && show) {
            show(downloadFull);
        }

    }

    private void showDownloadMissing(final boolean show) {
        Log.d(TAG, "showDownloadMissing ENTER");

        if (downloadMissing == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadMissing no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            builder.setMessage(res.getString(R.string.lebian_download_missing_note));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_continue_game), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadMissing = null;
                }
            });

            builder.setNegativeButton(res.getString(R.string.lebian_enable_now), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    finishActivitys(mContext);
                    platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                    platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                    downloadMissing = null;
                }
            });

            downloadMissing = builder.create();
            downloadMissing.setCancelable(false);
            downloadMissing.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }

        if(!downloadMissing.isShowing() && show) {
            show(downloadMissing);
        }

    }

    private void showDownloadAll(long size, final boolean show) {
        Log.d(TAG, "showDownloadAll ENTER");

        if (downloadAll == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadAll no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            lebian_download_all_note_switch_gnet = res.getString(R.string.lebian_download_all_note_switch_gnet);
            builder.setMessage(String.format(lebian_download_all_note_switch_gnet,((float)(size))/(1024.0f * 1024.0f)));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_continue_game), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadAll = null;
                    mContext.sendBroadcast(new Intent(getPackageName() + ".action.DOWNLOAD_ALL"), null);
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_SWITCH_MOBILE", 0), 1);
                }
            });

            builder.setNegativeButton(res.getString(R.string.lebian_download_not_now), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadAll = null;
                    mContext.sendBroadcast(new Intent(getPackageName() + ".action.DOWNLOAD_ALL_LATER"), null);
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_SWITCH_MOBILE", 0), 2);
                }
            });

            downloadAll = builder.create();
            downloadAll.setCancelable(false);
            downloadAll.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }

        if(!downloadAll.isShowing() && show) {
            downloadAll.setMessage(String.format(lebian_download_all_note_switch_gnet,((float)(size))/(1024.0f * 1024.0f)));
            show(downloadAll);
        }

    }

    private void showDownloadAllLater(final long size, final boolean zipExists, final boolean downloadZip, final boolean dataConnection, final boolean show) {
        Log.d(TAG, "showDownloadAllLater ENTER");

        if (downloadAllLater == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadAllLater no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            lebian_download_all_note = res.getString(R.string.lebian_download_all_note);
            lebian_download_all_note_al = res.getString(R.string.lebian_download_all_note_al);
            builder.setMessage(String.format(lebian_download_all_note,((float)(size))/(1024.0f * 1024.0f)));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_download_while_play), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadAllLater = null;
                    if(!zipExists && !downloadZip)
                        userDownload(mContext);
                    else
                        switchToDownloadFullRes(mContext, 1, false);
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_SECOND", 0), 1);
                }
            });

            if (getGlobalBoolean(mContext, "ENABLE_EXIT_BUTTON", false)) {
                 builder.setNegativeButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss(dialog);
                        finishActivitys(mContext);
                        platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                        platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                        downloadAllLater = null;
                        userClick(mContext, getInt(mContext, "DIALOG_TYPE_SECOND", 0), 2);
                    }
                });
            }

            downloadAllLater = builder.create();
            downloadAllLater.setCancelable(false);
            downloadAllLater.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }
        if(!downloadAllLater.isShowing() && show) {
            downloadAllLater.setMessage(String.format(dataConnection?lebian_download_all_note:lebian_download_all_note_al,((float)(size))/(1024.0f * 1024.0f)));
            show(downloadAllLater);
        }

    }

    private void showDownloadFullRes(long size, final boolean show) {
        showDownloadFullRes(size, 1, show, 0, false, null);
    }

    private void showDownloadFullRes(long size, final int zipType, final boolean show, final int triggerReason, boolean oneBtn, final Bundle bundle) {
        Log.d(TAG, "showDownloadFullRes ENTER");

        if (downloadFullRes == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadFullRes no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            int resId = triggerReason != 1 ? R.string.lebian_choose_by_user_bwbx : R.string.lebian_network_environment_poor;
            lebian_choose_by_user_bwbx = res.getString(R.string.lebian_choose_by_user_bwbx);
            lebian_network_environment_poor = res.getString(R.string.lebian_network_environment_poor);
            builder.setMessage(String.format(res.getString(resId),((float)(size))/(1024.0f * 1024.0f)));
            builder.setTitle(res.getString(R.string.lebian_hint));
            if(!getGlobalBoolean(mContext, "SHOW_DIALOG_BUTTON_BY_OLD_USER", false)){
                resId = R.string.lebian_exit_dialog_yes;
            }else{
                resId = R.string.lebian_download_now;
            }
            final String dialogKey = (triggerReason == 1) ? "DIALOG_TYPE_NET_POOR" :"DIALOG_TYPE_OLD_USER";
            builder.setPositiveButton(res.getString(resId), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadFullRes = null;
                    userClick(mContext, getInt(mContext, dialogKey, 0), 1);
                    switchToDownloadFullRes(mContext, zipType, false, bundle);
                }
            });
            if(!oneBtn&&!getGlobalBoolean(mContext, "SHOW_DIALOG_BUTTON_BY_OLD_USER", false)){
                builder.setNegativeButton(res.getString(R.string.lebian_exit_dialog_no), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss(dialog);
                        downloadFullRes = null;
                        userClick(mContext, getInt(mContext, dialogKey, 0), 2);
                    }
                });
            }else if (getGlobalBoolean(mContext, "ENABLE_EXIT_BUTTON", false)) {
                builder.setNegativeButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        platDo(getInt(mContext, "ACTION_TYPE_CANCEL_CHECK_FOREGROUND", 0));
                        platDo(getInt(mContext, "ACTION_TYPE_CLEAN_EXIT", 0));
                        dismiss(dialog);
                        downloadFullRes = null;
                        userClick(mContext, getInt(mContext, dialogKey, 0), 2);
                        killGameProcesses(mContext);
                    }
                });
            }

            downloadFullRes = builder.create();
            downloadFullRes.setCancelable(false);
            downloadFullRes.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }

        if(!downloadFullRes.isShowing() && show) {
            if (bundle != null && bundle.getLong("offset") > 0) {
                downloadFullRes.setPositiveButtonClick(new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d(TAG, "onClick: "+dialog+"  downloadFullRes:"+downloadFullRes);
                        dismiss(downloadFullRes);
                        if (dialog != null) {
                            dialog.dismiss();
                            setShowing(false);
                        }
                        downloadFullRes = null;
                        final String dialogKey = (triggerReason == 1) ? "DIALOG_TYPE_NET_POOR" : "DIALOG_TYPE_OLD_USER";
                        userClick(mContext, getInt(mContext, dialogKey, 0), 1);
                        switchToDownloadFullRes(mContext, zipType, false, bundle);
                    }
                });
            }
            downloadFullRes.setMessage(String.format(triggerReason != 1 ? lebian_choose_by_user_bwbx : lebian_network_environment_poor, ((float) (size)) / (1024.0f * 1024.0f)));
            show(downloadFullRes);
        }

    }

    private void showDownloadAllLaterInterface(final long size, final boolean zipExists, final boolean downloadZip, final boolean dataConnection, final boolean show) {
        Log.d(TAG, "showDownloadAllLaterInterface ENTER");

        if (downloadAllLaterInterface == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showDownloadAllLaterInterface no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            lebian_download_all_note_interface = res.getString(R.string.lebian_download_all_note_interface);
            builder.setMessage(String.format(lebian_download_all_note_interface,((float)(size))/(1024.0f * 1024.0f)));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadAllLaterInterface = null;
                    if(!zipExists && !downloadZip)
                        userDownload(mContext);
                    else
                        switchToDownloadFullRes(mContext, 1, false);
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_SECOND_INTERFACE", 0), 1);
                }
            });
            builder.setNegativeButton(res.getString(R.string.lebian_button_cancel), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    downloadAllLaterInterface = null;
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_SECOND_INTERFACE", 0), 2);
                }
            });
            downloadAllLaterInterface = builder.create();
            downloadAllLaterInterface.setCancelable(false);
            downloadAllLaterInterface.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }
        if(!downloadAllLaterInterface.isShowing() && show) {
            downloadAllLaterInterface.setMessage(String.format(lebian_download_all_note_interface,((float)(size))/(1024.0f * 1024.0f)));
            show(downloadAllLaterInterface);
        }

    }

    private void showRemainingResDownloading(final long size, final boolean show) {
        Log.d(TAG, "showRemainingResDownloading ENTER");

        if (remainingResDowning == null || !show) {
            Resources res = getResources(mContext);
            if(getTopActivity(mContext) == null){
                Log.d(TAG, "showRemainingResDownloading no topActivity");
                return;
            }
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext, getTopActivity(mContext));
            lebian_remaining_res_downloading = res.getString(R.string.lebian_remaining_res_downloading);
            builder.setMessage(String.format(lebian_remaining_res_downloading,((float)(size))/(1024.0f * 1024.0f)));
            builder.setTitle(res.getString(R.string.lebian_hint));
            builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss(dialog);
                    remainingResDowning = null;
                    userClick(mContext, getInt(mContext, "DIALOG_TYPE_REMAINING_RES_DOWNLOADING", 0), 1);
                }
            });
            remainingResDowning = builder.create();
            remainingResDowning.setCancelable(false);
            remainingResDowning.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                    if (keyCode == KeyEvent.KEYCODE_SEARCH){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
        }
        if(!remainingResDowning.isShowing() && show) {
            remainingResDowning.setMessage(String.format(lebian_remaining_res_downloading,((float)(size))/(1024.0f * 1024.0f)));
            show(remainingResDowning);
        }

    }


    private String getPackageName() {
        //android.app.Application app = (android.app.Application)mContext;
        return mContext.getPackageName();
    }

    private void startService(Intent intent,Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method startService = bwbxUtil.getDeclaredMethod("startService", Intent.class, Context.class);
            startService.setAccessible(true);
            startService.invoke(null, intent, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Activity getTopActivity(Context context) {
        Activity activity = null;
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method getTopActivity = bwbxUtil.getDeclaredMethod("getTopActivity", (Class[])null);
            getTopActivity.setAccessible(true);
            activity = (Activity) getTopActivity.invoke(null, (Object[])null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return activity;
    }

    public static boolean isLBMainOnTop(Context context){
        boolean result = false;
        try {
            Class<?> preferencesHelper = BwbxUI.getClass("life.LifeCycleHelper", false, context.getClassLoader());
            Method isLBMainOnTop = preferencesHelper.getDeclaredMethod("isLBMainOnTop", new Class[] {Context.class});
            isLBMainOnTop.setAccessible(true);
            result = (boolean) isLBMainOnTop.invoke(null, new Object[]{(Context)context});
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean isForeground(Context context) {
        boolean isForeground = false;
        try {
            Class<?> preferencesHelper =  BwbxUI.getClass("life.LifeCycleHelper", false, context.getClassLoader());
            Method isForegroundMethod = preferencesHelper.getDeclaredMethod("isForeground", new Class[] {Context.class});
            isForegroundMethod.setAccessible(true);
            isForeground = (boolean) isForegroundMethod.invoke(null, new Object[]{(Context)context});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isForeground;
    }

    public static void finishActivitys(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method finishActivitys = bwbxUtil.getDeclaredMethod("finishActivitys", (Class[])null);
            finishActivitys.setAccessible(true);
            finishActivitys.invoke(null, (Object[])null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchToDownloadFullRes(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method switchToDownloadFullRes = bwbxUtil.getDeclaredMethod("switchToDownloadFullRes", Context.class);
            switchToDownloadFullRes.setAccessible(true);
            switchToDownloadFullRes.invoke(null, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchToDownloadFullRes(Context context, int zipType) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method switchToDownloadFullRes = bwbxUtil.getDeclaredMethod("switchToDownloadFullRes", new Class[] {Context.class, int.class});
            switchToDownloadFullRes.setAccessible(true);
            switchToDownloadFullRes.invoke(null, new Object[]{(Context)context, (int)zipType});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchToDownloadFullRes(Context context, int zipType, boolean start) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method switchToDownloadFullRes = bwbxUtil.getDeclaredMethod("switchToDownloadFullRes", new Class[] {Context.class, int.class, boolean.class});
            switchToDownloadFullRes.setAccessible(true);
            switchToDownloadFullRes.invoke(null, new Object[]{context, zipType, start});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchToDownloadFullRes(Context context, int zipType, Bundle bundle) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method switchToDownloadFullRes = bwbxUtil.getDeclaredMethod("switchToDownloadFullRes", new Class[] {Context.class, int.class, Bundle.class});
            switchToDownloadFullRes.setAccessible(true);
            switchToDownloadFullRes.invoke(null, new Object[]{(Context)context, (int)zipType, (Bundle)bundle});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchToDownloadFullRes(Context context, int zipType, boolean start, Bundle bundle) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method switchToDownloadFullRes = bwbxUtil.getDeclaredMethod("switchToDownloadFullRes", new Class[]{Context.class, int.class, boolean.class, Bundle.class});
            switchToDownloadFullRes.setAccessible(true);
            switchToDownloadFullRes.invoke(null, new Object[]{(Context) context, (int) zipType, start, (Bundle) bundle});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void killGameProcesses(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("base.BaseUtil", false, context.getClassLoader());
            Method killGameProcesses = bwbxUtil.getDeclaredMethod("killGameProcesses", Context.class);
            killGameProcesses.setAccessible(true);
            killGameProcesses.invoke(null, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean getBoolean(Context context, String key, boolean defVal) {
        boolean ret = defVal;
        try {
            Class<?> clazz = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Field f = clazz.getDeclaredField(key);
            ret = f.getBoolean(null);
        } catch (Exception e) {
            //e.printStackTrace();
        }

        return ret;
    }

    public static int getInt(Context context, String key, int defVal) {
        int ret = defVal;
        try {
            Class<?> clazz = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Field f = clazz.getDeclaredField(key);
            ret = f.getInt(null);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return ret;
    }

    public static String getString(Context context, String key, String defVal) {
        String ret = defVal;
        try {
            Class<?> clazz = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Field f = clazz.getDeclaredField(key);
            ret = f.get(null).toString();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return ret;
    }

    public static void userRetry(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method userRetry = bwbxUtil.getDeclaredMethod("userRetry", (Class[])null);
            userRetry.setAccessible(true);
            userRetry.invoke(null, (Object[])null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void userClick(Context context, final int type, final int clickType) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method userClick = bwbxUtil.getDeclaredMethod("userClick", new Class[] {int.class, int.class});
            userClick.setAccessible(true);
            userClick.invoke(null, new Object[]{(int)type, (int)clickType});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void dialogRejected(Context context, final int type) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method dialogRejected = bwbxUtil.getDeclaredMethod("dialogRejected", new Class[] {int.class});
            dialogRejected.setAccessible(true);
            dialogRejected.invoke(null, new Object[]{(int)type});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void userDownload(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method userDownload = bwbxUtil.getDeclaredMethod("userDownload", (Class[])null);
            userDownload.setAccessible(true);
            userDownload.invoke(null, (Object[])null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downloadAll(Context context, final boolean checkNet) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method downloadAll = bwbxUtil.getDeclaredMethod("downloadAll", boolean.class);
            downloadAll.setAccessible(true);
            downloadAll.invoke(null, checkNet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void userAction(Context context, final int type, final int data) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method userAction = bwbxUtil.getDeclaredMethod("userAction", new Class[] {int.class, int.class});
            userAction.setAccessible(true);
            userAction.invoke(null, new Object[]{(int)type, (int)data});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downloadFullRes(Context context) {
        try {
            Class<?> bwbxUtil = BwbxUI.getClass("main.bwbx.BwbxUtil", false, context.getClassLoader());
            Method downloadFullRes = bwbxUtil.getDeclaredMethod("downloadFullRes", Context.class);
            downloadFullRes.setAccessible(true);
            downloadFullRes.invoke(null, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean getGlobalBoolean(Context context, String key, boolean defVal) {
        boolean ret = defVal;
        try {
            Class<?> clazz = Class.forName("com.excelliance.open.GlobalSettings", false, context.getClassLoader());
            Field f = clazz.getDeclaredField(key);
            ret = f.getBoolean(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ret = PreferencesHelper.getBoolean(context, PreferencesHelper.MODULE_GLOBAL_SETTINGS, key, ret);
        return ret;
    }

    public static int getGlobalInt(Context context, String key, int defVal) {
        int ret = defVal;
        try {
            Class<?> clazz = Class.forName("com.excelliance.open.GlobalSettings", false, context.getClassLoader());
            Field f = clazz.getDeclaredField(key);
            ret = f.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ret = PreferencesHelper.getInt(context, PreferencesHelper.MODULE_GLOBAL_SETTINGS, key, ret);
        return ret;
    }


    public static boolean isConnected(Context context) {
        boolean result = true;
        try {
            Class<?> networkUtil = BwbxUI.getClass("base.NetworkUtil", false, context.getClassLoader());
            Method isConnected = networkUtil.getDeclaredMethod("isConnected", Context.class);
            isConnected.setAccessible(true);
            Boolean ret = (Boolean) isConnected.invoke(null, context);
            result = ret.booleanValue();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean isWifi(Context context) {
        boolean result = true;
        try {
            Class<?> networkUtil = BwbxUI.getClass("base.NetworkUtil", false, context.getClassLoader());
            Method isWifi = networkUtil.getDeclaredMethod("isWifi", Context.class);
            isWifi.setAccessible(true);
            Boolean ret = (Boolean) isWifi.invoke(null, context);
            result = ret.booleanValue();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static int getBehavior(Context context, int target) {
        int behhavior = -1;

        try {
            Class<?> clazz = BwbxUI.getClass("main.AbTestManager", false, context.getClassLoader());
            Method getInstance = clazz.getDeclaredMethod("getInstance", Context.class);
            getInstance.setAccessible(true);
            Object bu = getInstance.invoke(null, context);
            Method getUrlRoot = clazz.getDeclaredMethod("getBehavior", new Class[] {int.class});
            behhavior = (int) getUrlRoot.invoke(bu, new Object[]{(int)target});
            Log.d(TAG, "getBehavior: behhavior:"+behhavior);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return behhavior;
    }

    public static boolean isLandscape(Context context, String className) {
        int orientation = -1;
        try {
            ComponentName comp = new ComponentName(context.getPackageName(), className);
            ActivityInfo activityInfo = context.getPackageManager().getActivityInfo(comp, PackageManager.MATCH_DEFAULT_ONLY);
            orientation = activityInfo.screenOrientation;
        } catch (PackageManager.NameNotFoundException e2) {
            Log.d("SwitchView", "isLandscape: err");
            e2.printStackTrace();
        }
        Log.d("SwitchView", "orientation : "+orientation);
        if (orientation == -1) {
            return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
        }
        return orientation == 0 || orientation == 6 || orientation == 8; //landscape = 0 sensorLandscape = 6 reverseLandscape = 8
    }

    public static Resources getResources(Context context) {
        Resources res = null;
        try {
            Class<?> networkUtil = BwbxUI.getClass("main.PlatformResources", false, context.getClassLoader());
            Method getRes = networkUtil.getDeclaredMethod("getMainResources", Context.class);
            getRes.setAccessible(true);
            res = (Resources) getRes.invoke(null, context);
        } catch (Exception e) {
            Log.d(TAG, "getResources err:"+e);
            res = context.getResources();
        }
        Log.d(TAG, "getResources res:"+res);
        return res;
    }

    public static Resources getApkResources(Context context) {
        Resources res = null;
        try {
            Class<?> networkUtil = BwbxUI.getClass("main.PlatformResources", false, context.getClassLoader());
            Method getRes = networkUtil.getDeclaredMethod("getApkResources", Context.class);
            getRes.setAccessible(true);
            res = (Resources) getRes.invoke(null, context);
        } catch (Exception e) {
            Log.d(TAG, "getResources err:"+e);
            res = context.getResources();
        }
        Log.d(TAG, "getResources res:"+res);
        return res;
    }

    public static String getClassName(Context context, String name) {
        String className = "com.excelliance.lbsdk." + name;
        try {
            Class.forName(className, false, context.getClassLoader());
        } catch (Exception e) {
            try {
                Class.forName("com.excelliance.lebian." + name, false, context.getClassLoader());
                className = "com.excelliance.lebian." + name;
            } catch (Exception e1) {
                try {
                    Class.forName("com.excelliance.assetsonly." + name, false, context.getClassLoader());
                    className = "com.excelliance.assetsonly." + name;
                } catch (Exception e2) {
                }
            }
        }
        return className;
    }
    public static Class<?> getClass(String name, boolean initialize, ClassLoader loader) {
        Class<?> cls = null;
        try {
           cls = Class.forName("com.excelliance.lbsdk." + name, initialize, loader);
        } catch (Exception e) {
            try {
                cls = Class.forName("com.excelliance.lebian." + name, initialize, loader);
            } catch (Exception e1) {
                try {
                    cls = Class.forName("com.excelliance.assetsonly." + name, initialize, loader);
                } catch (Exception e2) {
                }
            }
        }
        return cls;
    }

    public static Class<?> getClass(String name) {
        Class<?> cls = null;
        try {
            cls = Class.forName("com.excelliance.lbsdk." + name);
        } catch (Exception e) {
            try {
                cls = Class.forName("com.excelliance.lebian." + name);
            } catch (Exception e1) {
                try {
                    cls = Class.forName("com.excelliance.assetsonly." + name);
                } catch (Exception e2) {
                }
            }
        }
        return cls;
    }

    private void dismiss(DialogInterface dialog) {
        if (dialog != null) {
            try {
                dialog.dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        setShowing(false);
    }

    private void show(Dialog dialog) {
        if (dialog != null) {
            dialog.show();
        }
        setShowing(true);
    }

    private void setShowing(boolean v) {
        showing.set(v);
    }

    private void registerFloatWindow(Application app,final boolean isRecord){
        Log.d(TAG, "registerFloatWindow enter");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            mRemainSize = PreferencesHelper.getLong(mContext, PreferencesHelper.MODULE_DLOADINFO, "downloaded_size_float_win", 0L);
            app.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }

                @Override
                public void onActivityStarted(Activity activity) {
                }

                @Override
                public void onActivityResumed(Activity activity) {
                    Log.d(TAG, "onActivityResumed: activity:"+activity);
                    if (isRecord) {
                        rfwResume(activity);
                    } else {
                        pfwResume(activity);
                    }

                }

                @Override
                public void onActivityPaused(Activity activity) {
                    Log.d(TAG, "onActivityPaused: activity:"+activity);
                    if (isRecord) {
                        rfwPause();
                    } else {
                        pfwPause();
                    }
                }

                @Override
                public void onActivityStopped(Activity activity) {
                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                }
            });
        }
    }

    private void pfwResume(Activity activity){
        mActivity = activity;
        pfw = null;
        if (!bwbxIsFinished && !canShowFloatWinLater) {
            pfw = new ProgressFloatWindow(mContext, activity);
            pfw.setRemainSize(mRemainSize);
            pfw.show();
            mFloatWinIsShowing = true;
        }
    }

    private void rfwResume(Activity activity){

        if (rfw != null) {
            rfw.dismiss();
            rfw.destroy();
            rfw = null;
        }
        rfw = new RecordFloatWindow(mContext, activity);
        rfw.show();
    }

    private void pfwPause(){
        mActivity = null;
        if (pfw != null) {
            pfw.dismiss();
            pfw.destroy();
        }
    }

    private void rfwPause(){
        if (rfw != null) {
            rfw.dismiss();
            rfw.destroy();
        }
    }

    public void hideProgress(Dialog dialog) {
        try {
            if(dialog != null) {
                if(dialog.isShowing()) {
                    Context context = ((ContextWrapper)dialog.getContext()).getBaseContext();
                    if(context instanceof Activity) {
                        if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed())
                            dialog.dismiss();
                    } else
                        dialog.dismiss();
                }
                dialog = null;
            }
        }catch (Exception e){
            Log.d(TAG, "hideProgress exception");
        }
    }
}

