package app.issue.commons;

import android.support.annotation.NonNull;
import android.util.Log;

import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.core.CrashlyticsCore;
import com.squareup.leakcanary.LeakCanary;

import dagger.android.support.DaggerApplication;
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

/**
 * @author abatra
 */

public abstract class BaseApplication extends DaggerApplication {

    protected abstract boolean isDebug();

    @Override
    public void onCreate() {
        super.onCreate();
        installLeakCanary();
        enableCrashlytics();
        plantTimber();
    }

    private void plantTimber() {
        Timber.plant(isDebug() ? new Timber.DebugTree() : createReleaseTree());
    }

    private void installLeakCanary() {
        if (!LeakCanary.isInAnalyzerProcess(this)) {
            LeakCanary.install(this);
        }
    }

    private void enableCrashlytics() {
        CrashlyticsCore core = new CrashlyticsCore.Builder()
                .disabled(isDebug())
                .build();

        Crashlytics crashlytics = new Crashlytics.Builder()
                .core(core)
                .build();

        Fabric.with(this, crashlytics);
    }

    private Timber.Tree createReleaseTree() {
        return new Timber.Tree() {
            @Override
            protected void log(int priority, String tag, @NonNull String message, Throwable t) {
                if (priority != Log.VERBOSE && priority != Log.DEBUG) {
                    Crashlytics.log(priority, tag, message);
                    if (t != null) {
                        Crashlytics.logException(t);
                    }
                }
            }
        };
    }
}
