package com.sheep.jiuyan.samllsheep;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.multidex.MultiDex;

import com.kfzs.duanduan.ActMain;
import com.kfzs.duanduan.react.ConfigUtil;
import com.kfzs.duanduan.react.SharedPreferences;
import com.sheep.gamegroup.di.components.DaggerNetComponent;
import com.sheep.gamegroup.di.components.NetComponent;
import com.sheep.gamegroup.di.modules.NetModule;
import com.sheep.gamegroup.usage.AppUsageManager;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.AppUtil;
import com.sheep.gamegroup.util.ChannelContent;
import com.sheep.gamegroup.util.ConnectAddress;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.ScreenShotListenManager;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.activity.LoginAct;
import com.sheep.jiuyan.samllsheep.service.DownloadService;
import com.sheep.jiuyan.samllsheep.service.FloatService;
import com.sheep.jiuyan.samllsheep.service.FloatShotScreenService;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.smtt.sdk.QbSdk;

import rx.functions.Action1;

/**
 * Created by kemllor on 2017/12/21.
 */

public class SheepApp extends BaseApplication {

    public static Context mContext;
    public static SheepApp mSheepApp;
    public ConnectAddress connectAddress;


    private NetComponent netComponent;
    private boolean isShowQB;
    private String packgeName;
    private boolean isInitMidong = false;
    private boolean isShowMidong = false;
    private int midongTimeCount = 1;

    public int getMidongTimeCount() {
        return midongTimeCount;
    }

    public void setMidongTimeCount(int midongTimeCount) {
        this.midongTimeCount = midongTimeCount;
    }

    public boolean isShowMidong() {
        return isShowMidong;
    }

    public void setShowMidong(boolean showMidong) {
        isShowMidong = showMidong;
    }

    public boolean isInitMidong() {
        return isInitMidong;
    }

    public void setInitMidong(boolean initMidong) {
        isInitMidong = initMidong;
    }

    public String getPackgeName() {
        return packgeName;
    }

    public void setPackgeName(String packgeName) {
        this.packgeName = packgeName;
    }

    public boolean isShowQB() {
        return isShowQB;
    }

    public void setShowQB(boolean showQB) {
        isShowQB = showQB;
    }

    public static SheepApp get(Context context) {


        return (SheepApp) context.getApplicationContext();
    }

    public ConnectAddress getConnectAddress() {
        return connectAddress;
    }

    public void setConnectAddress(ConnectAddress connectAddress) {
            if(this.connectAddress != connectAddress){
                SharedPreferences.getInstance().putString("flavor", connectAddress.name());
                quit();
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            } else {
                G.showToast("已经是该服务器");
            }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(AppUtil.isMainProcess(this)) {
            mContext = getApplicationContext();
            mSheepApp = this;
            connectAddress = ConnectAddress.sheep.getDefultConnectAddress();
            registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
            initNet();
            QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
                @Override
                public void onCoreInitFinished() {
                    LogUtil.println("SheepApp", "QbSdk", "initX5Environment", "onCoreInitFinished");
                }

                @Override
                public void onViewInitFinished(boolean b) {
                    LogUtil.println("SheepApp", "QbSdk", "initX5Environment", "onViewInitFinished", b);

                }
            });
            ChannelContent.getInstance().initChannelContent(this);
        }
    }

    private void initNet() {
        netComponent = DaggerNetComponent.builder().netModule(new NetModule()).build();
    }


    public int mActivityCount;//显示的activity的个数, 0个时代表暂停或退出应用，1个代表应用正显示在用户面前
    private boolean notStop = false;
    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        private ScreenShotListenManager manager;
        @Override
        public void onActivityCreated(final Activity activity, Bundle savedInstanceState) {
            ActivityManager.getInstance().pushActivity(activity);
            if(/*activity instanceof SplashAct || */activity instanceof LoginAct){
                SysAppUtil.showVersionInfo(activity, SpUtils.getIgnoreMd5());
            } else if(activity instanceof ActMain){
                SysAppUtil.showVersionInfo(activity, SpUtils.getIgnoreMd5(), new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Jump2View.getInstance().tryShowHalfScreenAd(activity, ((ActMain) activity).getContainer());
                    }
                });
            }

            if(mActivityCount == 0) {
                if(ConfigUtil.getInstance().isUpgrade()) {
                    Beta.autoDownloadOnWifi = !BuildConfig.DEBUG;
                    Bugly.init(getApplicationContext(), Config.BUGLY_APPID, BuildConfig.DEBUG);
                }
                AppUsageManager.getInstance().needOpenLookAppUsageStatsPermisson(true);//尝试保存应用使用情况的数据
                LogUtil.println("SheepApp onActivityCreated", mActivityCount);
                if(DataUtil.IS_LISTEN_SCREEN_SHOT) {
                    manager = ScreenShotListenManager.newInstance(context);
                    manager.setListener(
                            new ScreenShotListenManager.OnScreenShotListener() {
                                public void onShot(String imagePath) {
                                    DataUtil.getInstance().addPng(imagePath);
                                }
                            }
                    );
                    manager.startListen();
                }
                UMConfigUtils.Event.SHEEP_CREATED.onEvent();
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            mActivityCount++;
            UMConfigUtils.onPageStart(activity);
            if (mActivityCount > 0) {
                if(!notStop) {
                    notStop = true;
                    LogUtil.println("SheepApp onActivityStarted", mActivityCount);
                    UMConfigUtils.Event.SHEEP_STARTED.onEvent();
                    Jump2View.getInstance().startFloat(activity, false);
                    Jump2View.getInstance().startShotScreenFloat(activity, false);
                }
            }
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            mActivityCount--;
            UMConfigUtils.onPageEnd(activity);
            if (mActivityCount <= 0) {
                if(notStop) {
                    notStop = false;
                    LogUtil.println("SheepApp onActivityStopped", mActivityCount);
                    UMConfigUtils.Event.SHEEP_STOPPED.onEvent();
                    Jump2View.getInstance().startFloat(activity, true);
                    Jump2View.getInstance().startShotScreenFloat(activity, true);
                }
            }
        }

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

        @Override
        public void onActivityDestroyed(Activity activity) {
            if(mActivityCount == 0) {
                LogUtil.println("SheepApp onActivityDestroyed", mActivityCount);
                stopService(new Intent(SheepApp.this, DownloadService.class));
                stopService(new Intent(SheepApp.this, FloatService.class));
                if(DataUtil.IS_USE_SCREEN_SHOT)
                    stopService(new Intent(SheepApp.this, FloatShotScreenService.class));
                if(manager != null)
                    manager.stopListen();
                UMConfigUtils.Event.SHEEP_DESTROYED.onEvent();
            }
        }
    };

    public NetComponent getNetComponent() {
        return netComponent;
    }

    public static SheepApp getInstance() {
        return mSheepApp;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}
