package org.deke.risk.riskahead.helper;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;

import org.deke.risk.riskahead.LoginActivity;
import org.deke.risk.riskahead.MapsActivity;
import org.deke.risk.riskahead.R;
import org.deke.risk.riskahead.ProfileActivity;
import org.deke.risk.riskahead.ReportWFActivity;
import org.deke.risk.riskahead.SettingsActivity;
import org.deke.risk.riskahead.SubscriptionsActivity;
import org.deke.risk.riskahead.ViewReportActivity;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 */
public abstract class BaseActivity extends AppCompatActivity {

    public final static String EXTRA_MESSAGE = "org.deke.risk.riskahead.MESSAGE";
    private final static String TAG = BaseActivity.class.getSimpleName();

    public final static int mainAvtivityID = 1;
    public final static int reportAvtivityID = 2;
    public final static int mapAvtivityID = 3;
    public final static int userstatsAvtivityID = 4;
    public final static int settingsAvtivityID = 5;
    public final static int subscriptionsAvtivityID = 6;
    public final static int logoutAvtivityID = 7;

    public SessionManager session;
    public HashMap<String, String> user;
    public Dialog pDialog;

    public InterstitialAd mInterstitialAd;

    public Drawer navDrawer = null;
    public Toolbar mToolbar;

    private BroadcastReceiver myReceiver;

    private static final int TIME_INTERVAL = 3000; // # milliseconds, desired time passed between two back presses.
    private long mBackPressed;

    int onStartCount = 0;

    public void userHasToBeLoggedIn() {
        if (!session.isLoggedIn()) {
            logout();
        }
        isNetworkAvailable();
    }

    public HashMap<String, String> getUser() {
        user = session.getUserDetails();
        return user;
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (onStartCount > 1) {
            this.overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);

        } else if (onStartCount == 1) {
            onStartCount++;
            onStartCount++;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        onStartCount = 1;
        if (savedInstanceState == null) {
            this.overridePendingTransition(R.anim.slide_in_left,
                    R.anim.slide_out_left);
        } else {
            onStartCount = 2;
        }

        setContentView(getLayoutResourceId());

        initAds();
        initProgressDialog();

        session = new SessionManager(getApplicationContext());
        user = session.getUserDetails();

        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        initNavigationDrawer(savedInstanceState);

        if (!isMyNotificationServiceRunning()) {
            Log.d(TAG, "onCreate: NotificationService not running. Starting service...");

            Intent wtdSServiceIntent = new Intent(this, NotificationService.class);
            PendingIntent wtdSServicePendingIntent = PendingIntent.getService(this, 0, wtdSServiceIntent, 0);

            long interval = DateUtils.MINUTE_IN_MILLIS * 3;
            long firstStart = System.currentTimeMillis();

            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            if (am != null){
                am.setInexactRepeating(AlarmManager.RTC, firstStart, interval, wtdSServicePendingIntent);
            }else{
                FirebaseCrashlytics.getInstance().log("AlarmManager in BaseActivity is null. No AlarmManager found.");
            }

            startService(new Intent(this, NotificationService.class));
        } else {
            Log.d(TAG, "onCreate: NotificationService already running. Not starting more services.");
        }

        AppRater.startAppRater(BaseActivity.this);
    }

    class LogoutReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("onReceive", "Logout in progress");
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerBroadcastReceiver();
    }

    public void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConfig.INTENT_LOGOUT);
        myReceiver = new LogoutReceiver();
        registerReceiver(myReceiver, intentFilter);
    }

    public void unregisterBroadcastReceiver() {
        try {
            unregisterReceiver(myReceiver);
        } catch (final Exception e) {
            FirebaseCrashlytics.getInstance().log("Exception caught: " + e);
            FirebaseCrashlytics.getInstance().recordException(e);
        }
    }

    private void initProgressDialog() {
        pDialog = new Dialog(this);
        pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        if(pDialog.getWindow() != null){
            pDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        }else{
            FirebaseCrashlytics.getInstance().log("ProgressDialog Window is null. Could not set BackgroundDrawable.");
        }

        pDialog.setContentView(R.layout.dialog_progresscircle);
    }

    private void initAds() {
        mInterstitialAd = new InterstitialAd(getApplicationContext());
        mInterstitialAd.setAdUnitId(getString(R.string.banner_ad_unit_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });

        requestNewInterstitial();
    }

    private void initNavigationDrawer(Bundle savedInstanceState) {
        PrimaryDrawerItem item2 = new PrimaryDrawerItem()
                .withName(R.string.navigation_report)
                .withIdentifier(reportAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_room);

        PrimaryDrawerItem item3 = new PrimaryDrawerItem()
                .withName(R.string.navigation_incident_map)
                .withIdentifier(mapAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_map);

        PrimaryDrawerItem item4 = new PrimaryDrawerItem()
                .withName(R.string.navigation_user_stats)
                .withIdentifier(userstatsAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_speaker_notes);

        PrimaryDrawerItem item5 = new PrimaryDrawerItem()
                .withName(R.string.navigation_acc_settings)
                .withIdentifier(settingsAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_settings);

        PrimaryDrawerItem item6 = new PrimaryDrawerItem()
                .withName(R.string.navigation_subscriptions)
                .withIdentifier(subscriptionsAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_star);

        PrimaryDrawerItem item7 = new PrimaryDrawerItem()
                .withName(R.string.navigation_logout)
                .withIdentifier(logoutAvtivityID)
                .withIcon(GoogleMaterial.Icon.gmd_remove_circle);

        AccountHeader headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.header2)
                .addProfiles(
                        new ProfileDrawerItem().withName(user.get("username")).withEmail(user.get("email")).withIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.logo_riskahead_header))
                )
                .build();

        navDrawer = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(headerResult)
                .withTranslucentStatusBar(true)
                .withHasStableIds(true)
                .withToolbar(mToolbar)
                .withOnDrawerListener(new Drawer.OnDrawerListener() {
                    @Override
                    public void onDrawerOpened(View drawerView) {
                    }

                    @Override
                    public void onDrawerClosed(View drawerView) {
                        androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
                        if (actionBar != null) actionBar.setTitle(getActivityName());
                    }

                    @Override
                    public void onDrawerSlide(View drawerView, float slideOffset) {

                    }
                })
                .withSavedInstance(savedInstanceState)
                .withSelectedItem(-1)
                .addDrawerItems(
                        item2,
                        item3,
                        new DividerDrawerItem(),
                        item4,
                        item5,
                        new DividerDrawerItem(),
                        item6,
                        item7).withOnDrawerItemClickListener((view, position, drawerItem) -> {

                            switch ((int) drawerItem.getIdentifier()) {
                                case 2:
                                    gotoReportActivity();
                                    return false;
                                case 3:
                                    gotoMapActivity();
                                    return false;
                                case 4:
                                    gotoProfileActivity();
                                    return false;
                                case 5:
                                    gotoSettingsActivity();
                                    return false;
                                case 6:
                                    gotoSubscriptionsActivity();
                                    return false;
                                case 7:
                                    logoutUser();
                                    break;
                                default:
                                    Log.e("Unknown switch page: ", Integer.toString(position));
                                    FirebaseCrashlytics.getInstance().log("AlarmManager in BaseActivity is null. No AlarmManager found.");
                                    break;
                            }

                            return false;
                        }).build();


    }

    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder().build();

        mInterstitialAd.loadAd(adRequest);
    }

    public void showAd() {
        if (session.getLastAddShown() == 0) session.setLastAddShown(System.currentTimeMillis());

        if (System.currentTimeMillis() > (session.getLastAddShown() + 120000)) {
            Log.d(TAG, "SHOW ADD!");
            if (mInterstitialAd.isLoaded()) {
                Log.d(TAG, "Loading Add...");
                if (!(session.getSubsNoAds() || session.getSubsPremium())) {

                    mInterstitialAd.show();
                    session.setLastAddShown(System.currentTimeMillis());

                } else {
                    Log.d(TAG, "Add not shown because user has status.");
                }
            }
        } else {
            Log.d(TAG, "SHOW NO ADD ( TIME NOT OUT ) !");
        }
    }

    public void isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo;

        if(connectivityManager != null){
            activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        }else{
            FirebaseCrashlytics.getInstance().log("Could not retrieve connectivityManager. Network Status can not be checked.");
            return;
        }

        // In case no activeNetworkInfo is found actually no standard network is present. Output message bos in that case
        if (activeNetworkInfo == null) {
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.alert_internetconnection_title))
                    .setMessage(getString(R.string.alert_internetconnection_text))
                    .setCancelable(false)
                    .setNeutralButton(android.R.string.yes, (dialog, which) -> logoutUser())
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }
    }

    public void logoutUser() {
        session.removeUser();
        logout();
    }

    public void handleVolleyErrorResponse() {
        showMessage(getString(R.string.errormsg_couldnotretrieve));
        //logoutUser();
    }

    public void logout() {
        session.setLogin(false);

        Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
        intent.putExtra(EXTRA_MESSAGE, AppConfig.INTENT_LOGIN);
        BaseActivity.this.startActivity(intent);

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(AppConfig.INTENT_LOGOUT);
        sendBroadcast(broadcastIntent);

        stopService(new Intent(BaseActivity.this, NotificationService.class));
        showAd();
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_common, menu);

        return true;
    }

    public void gotoReportActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), ReportWFActivity.class);
        startActivity(intent);
    }

    public void gotoReportActivity(String position) {
        Intent intent;
        intent = new Intent(getApplicationContext(), ReportWFActivity.class);
        intent.putExtra(EXTRA_MESSAGE, position);
        startActivity(intent);
        finish();
    }

    public void gotoMapActivity() {
        Intent intent;
        intent = new Intent(BaseActivity.this, MapsActivity.class);
        BaseActivity.this.startActivity(intent);
    }

    public void gotoMapActivity(String position) {
        Intent intent;
        intent = new Intent(getApplicationContext(), MapsActivity.class);
        intent.putExtra(EXTRA_MESSAGE, position);
        startActivity(intent);
    }

    public void getNotifyLocationFromMapActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), MapsActivity.class);
        intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETNOTIFY);
        startActivity(intent);
    }

    public void getIncidentLocationFromMapActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), MapsActivity.class);
        intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETINCLOC);
        startActivity(intent);
    }

    public void getNotifyLocationFromMapActivity(String position) {
        Intent intent;
        intent = new Intent(getApplicationContext(), MapsActivity.class);
        intent.putExtra(EXTRA_MESSAGE, position);
        intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETNOTIFY);
        startActivity(intent);
    }

    public void getIncidentLocationFromMapActivity(String position) {
        Intent intent;
        intent = new Intent(getApplicationContext(), MapsActivity.class);
        intent.putExtra(EXTRA_MESSAGE, position);
        intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETINCLOC);
        startActivity(intent);
    }

    public void gotoProfileActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), ProfileActivity.class);
        startActivity(intent);
    }

    public void gotoProfileActivity(String uid) {
        Intent intent;
        intent = new Intent(getApplicationContext(), ProfileActivity.class);
        intent.putExtra(EXTRA_MESSAGE, uid);
        startActivity(intent);
    }

    public void gotoSettingsActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), SettingsActivity.class);
        startActivity(intent);
    }

    public void gotoSubscriptionsActivity() {
        Intent intent;
        intent = new Intent(getApplicationContext(), SubscriptionsActivity.class);
        startActivity(intent);
    }

    public void gotoViewReportActivity(Integer uid) {
        Intent intent;
        intent = new Intent(getApplicationContext(), ViewReportActivity.class);
        intent.putExtra(EXTRA_MESSAGE, uid);
        startActivity(intent);
    }

    @Override
    protected void onPause(){
        super.onPause();
        unregisterBroadcastReceiver();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if ((id == R.id.menu_action_exit)) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if ((id == R.id.menu_action_about)) {
            showAboutInfoDialog();
        } else if ((id == R.id.menu_action_language)) {
            showLanguageDialog();
        } else if ((id == R.id.menu_action_help)) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.riskahead.net/contact/"));
            startActivity(browserIntent);
        } else if ((id == R.id.menu_action_feedback)) {
            showFeedbackDialog();
        }

        return super.onOptionsItemSelected(item);
    }

    private void showLanguageDialog() {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(R.string.txt_language_title);
        String[] types = {"ar - العربية", "de - Deutsch", "en - English", "es - Español", "et - Eesti keel", "fi - Suomi", "fr - Français", "lv - Latviešu valoda", "mn - Монгол хэл", "nl - Nederlands", "pl - Polszczyzna", "pt - Português do Brasil", "ru - Pусский", "tr - Türkçe"};
        b.setItems(types, (dialog, which) -> {

            dialog.dismiss();
            switch (which) {
                case 0:
                    setLocale("ar");
                    break;
                case 1:
                    setLocale("de");
                    break;
                case 2:
                    setLocale("en");
                    break;
                case 3:
                    setLocale("es");
                    break;
                case 4:
                    setLocale("et");
                    break;
                case 5:
                    setLocale("fi");
                    break;
                case 6:
                    setLocale("fr");
                    break;
                case 7:
                    setLocale("lv");
                    break;
                case 8:
                    setLocale("mn");
                    break;
                case 9:
                    setLocale("nl");
                    break;
                case 10:
                    setLocale("pl");
                    break;
                case 11:
                    setLocale("pt");
                    break;
                case 12:
                    setLocale("ru");
                    break;
                case 13:
                    setLocale("tr");
                    break;
            }
        });

        b.show();
    }

    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        Intent refresh = new Intent(this, this.getClass());
        startActivity(refresh);
        finish();
    }

    @SuppressLint("InflateParams")
    private void showAboutInfoDialog() {
        LayoutInflater inflater = getLayoutInflater();
        View dialoglayout = inflater.inflate(R.layout.dialog_about, null);

        ((TextView) dialoglayout.findViewById(R.id.txt_about_homepage)).setMovementMethod(LinkMovementMethod.getInstance());
        ((TextView) dialoglayout.findViewById(R.id.txt_about_privacy)).setMovementMethod(LinkMovementMethod.getInstance());
        ((TextView) dialoglayout.findViewById(R.id.txt_about_terms)).setMovementMethod(LinkMovementMethod.getInstance());

        try {
            ((TextView) dialoglayout.findViewById(R.id.lbl_about_version)).setText(String.format("Version: %s", getPackageManager().getPackageInfo(getPackageName(), 0).versionName));
        } catch (PackageManager.NameNotFoundException e) {
            FirebaseCrashlytics.getInstance().log("Exception caught");
            FirebaseCrashlytics.getInstance().recordException(e);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this)
                .setPositiveButton(android.R.string.yes, (dialog, which) -> {
                    //do nothing
                });

        builder.setView(dialoglayout);
        builder.show();
    }

    private void showFeedbackDialog() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(R.string.menu_action_feedback);
        alert.setMessage(R.string.txt_feedback_message);

        final EditText input = new EditText(BaseActivity.this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);


        input.setLayoutParams(lp);
        input.setLines(4);
        input.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.bootstrap_gray_lightest));
        input.setGravity(Gravity.TOP);
        input.setHint(R.string.txt_feedback_hint);

        alert.setIcon(R.drawable.logo_380);
        alert.setCancelable(true);
        alert.setPositiveButton(R.string.txt_feedback_sendbtn,
                (dialog, which) -> sendFeedback(input.getText().toString()));
        alert.setNegativeButton(R.string.txt_feedback_cancelbtn,
                (dialog, which) -> {
                    // do nothing
                });

        AlertDialog ad = alert.create();
        ad.setView(input, 0, 50, 0, 20);
        ad.show();
    }

    private void sendFeedback(String feedback) {
        StringBuilder sysprop = new StringBuilder();

        java.util.Properties props = System.getProperties();
        java.util.Enumeration e = props.propertyNames();
        while (e.hasMoreElements()) {
            String k = (String) e.nextElement();
            String v = props.getProperty(k);
            sysprop.append(k).append(": ").append(v).append("\n");
        }


        StringRequest strReq = getStringRequestSendFeedback(feedback, sysprop.toString());
        String tag_string_req = "reqsendfeedback";
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private StringRequest getStringRequestSendFeedback(final String feedback, final String sysprop) {
        return new StringRequest(Request.Method.POST, AppConfig.REST_SEND_FEEDBACK, response -> {
            Log.d(TAG, "Send Feedback: " + response);

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) {
                    showMessage(getString(R.string.txt_feedback_response));
                } else {
                    String errorMsg = jObj.getString("error_msg");
                    FirebaseCrashlytics.getInstance().log("Error sending feedback (server returned error): " + errorMsg);
                }
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("Exception caught: " + e);
                FirebaseCrashlytics.getInstance().recordException(e);
            }

        }, error -> FirebaseCrashlytics.getInstance().log("Error sending feedback: " + error.getMessage())) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("uid", user.get(SessionManager.KEY_UID));
                params.put("token", user.get(SessionManager.TOKEN));
                params.put("feedback", feedback);
                params.put("systemprop", sysprop);
                return params;
            }
        };
    }

    public void showMessage(String statusText) {
        Toast.makeText(this, statusText, Toast.LENGTH_LONG).show();
    }

    protected abstract int getLayoutResourceId();

    protected abstract String getActivityName();

    public void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    public void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    private boolean isMyNotificationServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        if(manager != null){
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (NotificationService.class.getName().equals(service.service.getClassName())) return true;
            }
        }else{
            FirebaseCrashlytics.getInstance().log("Could not retrieve Activity_Service Manager.");
        }

        return false;
    }

    @Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                showMessage(getString(R.string.txt_backpressed_msg));
            }

            mBackPressed = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    public void dropBreadCrumb(String category, String action, String label, long value) {
        String breadCrumb = String.format("%s|%s|%s|%s", category, action, label, value);
        FirebaseCrashlytics.getInstance().log(breadCrumb);
    }
}
