package cgmblelib.base;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import androidx.core.text.TextUtilsCompat;
import androidx.core.view.ViewCompat;

import java.util.Locale;

import cgmblelib.utils.CrashHandler;
import cgmblelib.utils.MyLog;
import cgmblelib.utils.Tool;


/**
 * @author minyuchun
 * @date 2018/3/22
 * 基础的Application 类库
 */
public class BApplication extends Application {

    //长期持有以下对象不清除回造成内存泄漏问题，一般不建议这样长期持有
    @SuppressLint("StaticFieldLeak")
    static Context sContext;
    @SuppressLint("StaticFieldLeak")
    protected static BApplication sApp;
    /**
     * APP是否在前台
     */
    protected static boolean isForeground = false;

    /**
     * activity lifecycle callback
     */

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("BApplication", "BApplication onCreate called");

        sContext = getApplicationContext();
        sApp = this;

        MyLog.initSpecial();
        MyLog.setIsDebug(Tool.isApkInDebug(this));
        CrashHandler handler = new CrashHandler();
        Thread.setDefaultUncaughtExceptionHandler(handler);
    }

    public static boolean isRtl() {
        return TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL;
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    // Add a method to manually set the context
    public static void setContext(Context context) {
        if (context != null) {
            sContext = context.getApplicationContext();
            Log.d("BApplication", "Context manually set");
        }
    }

    public static Context getContext() {
        if (sContext == null) {
            throw new NullPointerException("你需要在你的项目中集成App，并且在AndroidManifest.xml中应用");
        }
        return sContext;
    }

    /**
     * 获取全局上下文
     *
     * @return
     */
    public static BApplication getApp() {
        return sApp;
    }

}
