package com.duben.microtribe;

import android.content.Context;
import android.content.Intent;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.downloader.PRDownloader;
import com.downloader.PRDownloaderConfig;
import com.duben.microtribe.ad.TTAdManagerHolder;
import com.duben.microtribe.common.Constant;
import com.duben.microtribe.manager.TXCSDKService;
import com.duben.microtribe.manager.TalkingDataManager;
import com.duben.microtribe.net.LoanService;
import com.duben.microtribe.net.V6Service;
import com.duben.microtribe.utils.AppPreferencesManager;
import com.duben.microtribe.utils.ForegroundOrBackground;
import com.duben.microtribe.utils.MateUtils;
import com.duben.oaid.MiitHelper;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.tencent.bugly.crashreport.CrashReport;

import rx.Scheduler;
import rx.schedulers.Schedulers;

/**
 * 描述：Application
 * 作者：孟崔广
 * 时间：2020/6/15 17:40
 */
public class MintsApplication extends MultiDexApplication {

    private static Context mContext;
    public static String OAID = "";
    private static LocalBroadcastManager mLocalBroadcatManager;
    private Scheduler defaultSubscribeScheduler;
    private LoanService loanService;
    private V6Service v6Service;

    /**
     * 获取全局context
     */
    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getApplicationContext();

        // 三方配置
        thirdConfig();
    }

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

    /**
     * 三方配置
     */
    public void thirdConfig() {
        // 未同意权限弹窗，不进行SDK初始化
        if (AppPreferencesManager.INSTANCE.get()
                .getBoolean(Constant.LOAN_PERMISSION_FLAG, true)) return;

        // 判断应用是否在前台
        ForegroundOrBackground.init(this);

        initMiitHelper();

        TTAdManagerHolder.init(this);

        TXCSDKService.init(this);

        TalkingDataManager.INSTANCE.init(this);

        // PR下载附件
        initPRDownloader();

        //logger
        BindLogger();

        // bugly
        CrashReport.initCrashReport(this, "d035276c5b", BuildConfig.DEBUG);
    }

    /**
     * PR下载附件
     */
    private void initPRDownloader() {
        PRDownloaderConfig config = PRDownloaderConfig.newBuilder()
                .setDatabaseEnabled(true)
                .build();
        PRDownloader.initialize(this, config);
    }

    /**
     * 自定义logger
     */
    private void BindLogger() {
        //自定义logger
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  //是否选择显示线程信息，默认为true
                .methodCount(0)         //方法数显示多少行，默认2行
                .methodOffset(7)        //隐藏方法内部调用到偏移量，默认5
                // .logStrategy(customLog) //打印日志的策略，默认LogCat
                .tag("mints---network")   //自定义TAG全部标签，默认PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
    }

    /**
     * app退出
     */
    public void exitApp() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_EXIT_APP);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        MintsApplication.getLocalBroadcastManager().sendBroadcast(intent);

        System.gc();
    }

    /**
     * 获得LocalBroadcastManager对象
     *
     * @return LocalBroadcastManager对象
     */
    public static LocalBroadcastManager getLocalBroadcastManager() {
        if (mLocalBroadcatManager == null) {
            mLocalBroadcatManager = LocalBroadcastManager.getInstance(mContext);
        }
        return mLocalBroadcatManager;
    }

    public LoanService getLoanService() {
        if (loanService == null) {
            loanService = LoanService.Factory.create(this);
        }
        return loanService;
    }

    public V6Service getV6Service() {
        if (v6Service == null) {
            v6Service = V6Service.Factory.create();
        }
        return v6Service;
    }

    public Scheduler defaultSubscribeScheduler() {
        if (defaultSubscribeScheduler == null) {
            defaultSubscribeScheduler = Schedulers.io();
        }
        return defaultSubscribeScheduler;
    }

    /**
     * 移动安装联盟 获取OAID等设备标识符
     */
    private void initMiitHelper() {
        try {
            MiitHelper miitHelper = new MiitHelper(new MiitHelper.AppIdsUpdater() {

                @Override
                public void onIdsValid(String ids) {
                    MintsApplication.OAID = ids;

                    System.out.println("123123123 oaid=" + ids);
                }
            });
            miitHelper.getDeviceIds(MintsApplication.getContext(), true, true, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
