package com.sensetime.demo;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.sensetime.mtc.MClient;
import com.sensetime.mtc.MtcCode;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import java.lang.ref.WeakReference;
import java.util.Stack;

/**
 * Author:Created by LaoTie on 2019/12/12.
 * Enterprise:SenseTime
 **/
public class SenseTimeApp extends Application {
    public static final String TAG = "SenseTimeApp";

    private MClient mClient = MClient.getInstance();
    private SenseTimeMtc senseTimeMtc = SenseTimeMtc.getInstance();

    private CheckConnectRunnable checkConnectRunnable = new CheckConnectRunnable();
    private Thread checkConnectThread = new Thread(checkConnectRunnable);


    private static int FIRST_ACTIVITY_CREATED_NUM = 0;
    private Stack<WeakReference<Activity>> activityList = new Stack<WeakReference<Activity>>();

    private SparseArray<String> selectedImagePaths;
    private RefWatcher refWatcher;
    private boolean isExitApp = false;

    public static int getFirstActivityCreatedNum(){
        return FIRST_ACTIVITY_CREATED_NUM;
    }
    public static void incrementFirstActivityCreatedNum(){
        FIRST_ACTIVITY_CREATED_NUM++;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Utils.init(this);
        initLogger();
        LogUtils.eTag(TAG, "onCreate");
        FIRST_ACTIVITY_CREATED_NUM = 0;

        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        refWatcher = LeakCanary.install(this);
        isExitApp = false;
        //cancel find device thread
        //checkConnectThread.start();
    }


    private class CheckConnectRunnable implements Runnable {

        @Override
        public void run() {
            while (!isExitApp) {
                String dev = senseTimeMtc.getDevicePath();
                if (!TextUtils.isEmpty(dev)) {//note 有节点
                    MtcCode mtcCode = mClient.mtcPing();
                    LogUtils.vTag(TAG, "mtcCode:" + mtcCode);
                    if (mtcCode != MtcCode.SUCCESS) {//ping失败了，串口有问题，试图重连
                        senseTimeMtc.initMtc(() -> {
                        });
                    }
                }

                try {
                    Thread.sleep(1000 * 5);
                } catch (InterruptedException e) {
                    LogUtils.eTag(TAG, e.getMessage());
                }
            }
        }
    }



    /**
     * 根据不同的版本初始化日志模块
     */
    private void initLogger() {
        mClient.mtcSetIsDebug(true);
        LogUtils.getConfig()
                .setGlobalTag("SenseEngineDemo")
                .setLogSwitch(true)
                .setSingleTagSwitch(true)
                .setLog2FileSwitch(true)
                .setConsoleSwitch(true)
                .setLogHeadSwitch(true)
                .setBorderSwitch(true);
        LogUtils.dTag(TAG, "Log2File path: " + LogUtils.getCurrentLogFilePath());
    }

    /**
     * 将Activity压入Application栈
     *
     * @param task 将要压入栈的Activity对象
     */
    public void pushTask(WeakReference<Activity> task) {
        int index = activityList.indexOf(task);
        activityList.push(task);
    }

    /**
     * 将传入的Activity对象从栈中移除
     *
     * @param task
     */
    public void removeTask(WeakReference<Activity> task) {
        activityList.remove(task);
    }

    @Override
    public void onTerminate() {
        LogUtils.eTag(TAG, "onTerminate");
        super.onTerminate();
        MClient.getInstance().mtcDestroy();
    }

    public void exitApp() {
        for (WeakReference<Activity> task : activityList) {
            Activity activity = task.get();
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
        isExitApp = true;
        System.exit(0);
    }

    public static RefWatcher getRefWatcher(Context context) {
        SenseTimeApp senseTimeApp = (SenseTimeApp) context.getApplicationContext();
        return senseTimeApp.refWatcher;
    }

    public SparseArray<String> getSelectedImagePaths() {
        return selectedImagePaths;
    }

    public void setSelectedImagePaths(SparseArray<String> selectedImagePaths) {
        this.selectedImagePaths = selectedImagePaths;
    }
}
