package com.sheep.jiuyan.samllsheep;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.liulishuo.okdownload.OkDownload;
import com.liulishuo.okdownload.core.dispatcher.DownloadDispatcher;
import com.qiniu.android.storage.UploadManager;
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.module.login.LoginAct;
import com.sheep.gamegroup.usage.AppUsageManager;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.AppUtil;
import com.sheep.gamegroup.util.CertificationUtil;
import com.sheep.gamegroup.util.ChannelContent;
import com.sheep.gamegroup.util.ConfigUtil;
import com.sheep.gamegroup.util.ConnectAddress;
import com.sheep.gamegroup.util.DataKey;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyFileNameGenerator;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.viewHelper.CacheImageUtil;
import com.sheep.gamegroup.view.activity.GameCertificationActivity;
import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
import com.sheep.jiuyan.samllsheep.service.DownloadService;
import com.sheep.jiuyan.samllsheep.service.FloatShotScreenService;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.youmi.android.offer.YmConfig;

import org.wysaid.common.Common;
import org.wysaid.nativePort.CGENativeLibrary;
import org.xutils.x;

import java.io.IOException;
import java.io.InputStream;

import cn.jpush.android.api.JPushInterface;

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

public class SheepApp extends MultiDexApplication {

    public static SheepApp mSheepApp;
    public ConnectAddress connectAddress;


    private NetComponent netComponent;
    private boolean isShowQB;
    private boolean isInitMidong = false;
    private boolean isShowMidong = false;
    private int midongTimeCount = 1;
    private String gameCode;//游戏code
    private String gamePackgeName;
    private boolean gameFlag;

    public boolean isGameFlag() {
        return gameFlag;
    }

    public void setGameFlag(boolean gameFlag) {
        this.gameFlag = gameFlag;
    }

    public String getGamePackgeName() {
        return gamePackgeName;
    }

    public void setGamePackgeName(String gamePackgeName) {
        this.gamePackgeName = gamePackgeName;
    }

    public String getGameCode() {
        return gameCode;
    }

    public void setGameCode(String gameCode) {
        this.gameCode = gameCode;
    }

    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 boolean isShowQB() {
        return isShowQB;
    }

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

    public ConnectAddress getConnectAddress() {
        return connectAddress;
    }

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

    private RefWatcher refWatcher;

    public static RefWatcher getRefWatcher() {
        return mSheepApp.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (AppUtil.isMainProcess(this)) {
            mSheepApp = this;
            connectAddress = ConnectAddress.sheep.getDefaultConnectAddress();
            registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
            initNet();
            initUtils();
            detectFileUriExposure();
            ChannelContent.getInstance().initChannelContent(this);

        }
        refWatcher = LeakCanary.install(this);
    }

    /**
     * https://bugly.qq.com/v2/crash-reporting/crashes/0dd998212c/21541?pid=1
     * #21541 android.os.FileUriExposedException
     * file:///storage/emulated/0/Sheep/com.woniu.wdqk.coolpad.kf689667873.apk exposed beyond app through Intent.getData()
     * com.sheep.jiuyan.samllsheep.utils.h.b(PackageUtil.java:103)
     * <p>
     * 解决方案
     * 因为buildsdk是>=24,所以调用Uri.fromFile时保错，解决方法：
     * <p>
     * 在application的onCreate里:
     * StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
     * StrictMode.setVmPolicy(builder.build());
     * builder.detectFileUriExposure()
     * <p>
     * SDK>24 和<24的解决方案
     * public static void openFile(Context context, File file) {
     * Intent intent = new Intent();
     * intent.setAction(android.content.Intent.ACTION_VIEW);
     * Uri uri;
     * if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
     * intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     * Uri contentUri = FileProvider.getUriForFile(context,
     * context.getApplicationContext().getPackageName() + ".provider",
     * file);
     * intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
     * } else {
     * uri = Uri.fromFile(file);
     * intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     * intent.setDataAndType(uri, "application/vnd.android.package-archive");
     * }
     * context.startActivity(intent);
     * }
     */
    private void detectFileUriExposure() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }

    private void initUtils() {
        RefreshUtil.newInstance().initRefresh();
        DisplayMetrics metric = getResources().getDisplayMetrics();
        G.DENSITY = metric.density;
        G.DENSITY_DPI = metric.densityDpi;
        boolean isHeightBig = metric.heightPixels > metric.widthPixels;
        G.HEIGHT = isHeightBig ? metric.heightPixels : metric.widthPixels;
        G.WIDTH = isHeightBig ? metric.widthPixels : metric.heightPixels;

        int resourceId = SheepApp.getInstance().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            G.BAR_HEIGHT = SheepApp.getInstance().getResources().getDimensionPixelSize(resourceId);
        } else {
            G.BAR_HEIGHT = (int) (25 * metric.density);//不准确的方法
        }
        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);

            }
        });
        x.Ext.init(this);
        x.Ext.setDebug(org.xutils.BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
//        ZXingLibrary.initDisplayOpinion(this);
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "5ab0a1da8f4a9d742900035f");
        UMShareAPI.get(this);
        PlatformConfig.setWeixin("wx2be7f59bb7bb963f", "6cf7ca0f6c6ac97c6961d901fee8adb9");
        PlatformConfig.setQQZone("101461115", "b874bc950bcf066f17fd52cf2bb959e9");

        //极光推送
        JPushInterface.setDebugMode(org.xutils.BuildConfig.DEBUG);
        JPushInterface.init(this);

        initBdLocationOption();

        //设置下载工具
        DownloadDispatcher.setMaxParallelRunningCount(1000);//在这里，下载框架好像有个bug，如果设置为5，第一个下载会占4个，第二个下载就只有一个在下载，就会失败

//        RemitStoreOnSQLite.setRemitToDBDelayMillis(3000);
        if(TestUtil.isDev())
            initCgeLibrary();
    }

    private void initCgeLibrary() {
        //The second param will be passed as the second arg of the callback function.
        //第二个参数根据自身需要设置， 将作为 loadImage 第二个参数回传
        CGENativeLibrary.setLoadImageCallback(mLoadImageCallback, null);
        for (String name : CGE_FILTER_IMGS) {
            CacheImageUtil.cacheImg(ViewUtil.getNetImgByNameAndSuffix(name), null);
        }
    }
    public static final String[] CGE_FILTER_IMGS = {"edgy_amber.png", "filmstock.png", "foggy_night.png", "late_sunset.png", "soft_warming.png", "wildbird.png", "hehe.jpg", "mapping0.jpg"};
    public CGENativeLibrary.LoadImageCallback mLoadImageCallback = new CGENativeLibrary.LoadImageCallback() {

        //Notice: the 'name' passed in is just what you write in the rule, e.g: 1.jpg
        //注意， 这里回传的name不包含任何路径名， 仅为具体的图片文件名如 1.jpg
        @Override
        public Bitmap loadImage(String name, Object arg) {
            String path = CacheImageUtil.getCacheImg(ViewUtil.getNetImgByNameAndSuffix(name));
            if (path != null) {
                return BitmapFactory.decodeFile(path);
            }
            return null;
        }

        @Override
        public void loadImageOK(Bitmap bmp, Object arg) {
            Log.i(Common.LOG_TAG, "Loading bitmap over, you can choose to recycle or cache");

            //The bitmap is which you returned at 'loadImage'.
            //You can call recycle when this function is called, or just keep it for further usage.
            //唯一不需要马上recycle的应用场景为 多个不同的滤镜都使用到相同的bitmap
            //那么可以选择缓存起来。
            bmp.recycle();
        }
    };

    private void initBdLocationOption() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数

        LocationClientOption option = new LocationClientOption();
        //经纬度
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，设置定位模式，默认高精度
//LocationMode.Hight_Accuracy：高精度；
//LocationMode. Battery_Saving：低功耗；
//LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
//可选，设置返回经纬度坐标类型，默认gcj02
//gcj02：国测局坐标；
//bd09ll：百度经纬度坐标；
//bd09：百度墨卡托坐标；
//海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
//可选，设置发起定位请求的间隔，int类型，单位ms
//如果设置为0，则代表单次定位，即仅定位一次，默认为0
//如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
//可选，设置是否使用gps，默认false
//使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
//可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
//可选，定位SDK内部是一个service，并放到了独立进程。
//设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(true);
//可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
//可选，7.2版本新增能力
//如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
//可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        //地址
        option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true

        mLocationClient.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.start();
    }

    public LocationClient mLocationClient = null;
    private SheepLocationListener myListener = new SheepLocationListener();

    //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
    //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文中的说明
    public class SheepLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location == null)
                return;
            curLocation = location;
            //获取经纬度
//            double latitude = location.getLatitude();    //获取纬度信息
//            double longitude = location.getLongitude();    //获取经度信息
//            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
//
//            String coorType = location.getCoorType();
//            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
//
//            int errorCode = location.getLocType();
//            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
//
//            //获取地址
//            String addr = location.getAddrStr();    //获取详细地址信息
//            String country = location.getCountry();    //获取国家
//            String province = location.getProvince();    //获取省份
//            String city = location.getCity();    //获取城市
//            String district = location.getDistrict();    //获取区县
//            String street = location.getStreet();    //获取街道信息
        }
    }

    private BDLocation curLocation;

    public BDLocation getCurLocation() {
        mLocationClient.restart();
        return curLocation;
    }

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


    private HttpProxyCacheServer proxy;

    //AndroidVideoCache 获取缓存代表服务器，可缓存视频
    //https://github.com/danikula/AndroidVideoCache
    public static HttpProxyCacheServer getHttpProxyCacheServer() {
        return mSheepApp.proxy == null ? (mSheepApp.proxy = mSheepApp.newHttpProxyCacheServer()) : mSheepApp.proxy;
    }

    private HttpProxyCacheServer newHttpProxyCacheServer() {
        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(2L * 1024 * 1024 * 1024)       // 2 Gb for cache
                .maxCacheFilesCount(20)////最多缓存个数
                .fileNameGenerator(new MyFileNameGenerator())
                .build();
    }

    public int mActivityCount;//显示的activity的个数, 0个时代表暂停或退出应用，1个代表应用正显示在用户面前
    private boolean notStop = false;
    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {

        @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 (YmConfig.isAvf(activity)) {
                YmConfig.showTipDialog(activity, YmConfig.TYPE_ADD_VIEW);
            }

            if (mActivityCount == 0) {
                if (ConfigUtil.getInstance().isUpgrade()) {
                    Beta.autoDownloadOnWifi = !BuildConfig.DEBUG;
                    Bugly.init(getApplicationContext(), Config.BUGLY_APPID, BuildConfig.DEBUG);
                }
                AppUsageManager.getInstance().needOpenLookAppUsageStatsPermission(true);//尝试保存应用使用情况的数据
                LogUtil.println("SheepApp onActivityCreated", activity.getClass().getSimpleName(), mActivityCount);
                if (!UMConfigUtils.isNotNeedAct(activity))
                    UMConfigUtils.Event.SHEEP_CREATED.onEvent();
            }
        }

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

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

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

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

        @Override
        public void onActivityDestroyed(Activity activity) {
            if (YmConfig.isAvf(activity)) {
                YmConfig.disTipDialog();
            }
            if (!TextUtils.isEmpty(gamePackgeName) && isGameFlag() && (activity instanceof GameCertificationActivity || activity instanceof LoginAct)) {
                setGameFlag(false);
                CertificationUtil.newInstance().doCertification(activity, null, gamePackgeName, "delete");
            }
            if (mActivityCount == 0) {
                LogUtil.println("SheepApp onActivityDestroyed", activity.getClass().getSimpleName(), mActivityCount);
                DataUtil.getInstance().resetIsNewSmallSheep();
                stopService(new Intent(SheepApp.this, DownloadService.class));
//                if (DataUtil.IS_LISTEN_SCREEN_SHOT) {
//                    stopService(new Intent(activity, ListenerShotService.class));
//                }
                stopService(new Intent(SheepApp.this, AutoCheckService.class));
                if (DataUtil.IS_USE_SCREEN_SHOT)
                    stopService(new Intent(SheepApp.this, FloatShotScreenService.class));
                DataUtil.putAsInt(DataKey.KEY_ORDER, 1);
                if (!UMConfigUtils.isNotNeedAct(activity))
                    UMConfigUtils.Event.SHEEP_DESTROYED.onEvent();
            }
            ActivityManager.getInstance().endActivity(activity);
        }
    };

    /**
     * quit app safe
     */
    public void quit() {
        try {
            OkDownload.with().downloadDispatcher().cancelAll();
            ActivityManager.getInstance().finishAllActivity();
        } catch (Exception ignore) {
        }
    }

    public NetComponent getNetComponent() {
        return netComponent;
    }

    public static SheepApp getInstance() {
        return mSheepApp;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        /* 内存不足时让Glide清空内存缓存数据 */
        Glide.get(this).clearMemory();
        LogUtil.println("SheepApp", "onLowMemory");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory();
        }
        Glide.get(this).onTrimMemory(level);
        LogUtil.println("SheepApp", "onTrimMemory");
    }

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

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

}
