package it.integry.integrywmsnative.core.utility;

import android.app.Dialog;
import android.content.Context;
import android.text.Html;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.orhanobut.logger.Logger;

import it.integry.integrywmsnative.BuildConfig;
import it.integry.integrywmsnative.core.rest.CommonRESTException;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class UtilityExceptions {


    public static void defaultException(Context context, Exception ex, Dialog progressDialog) {
        defaultException(context, ex);
        if (progressDialog != null) progressDialog.dismiss();
    }

    public static void defaultException(Context context, Exception ex) {
        defaultException(context, ex, false);
    }

    public static void defaultException(Context context, Exception ex, boolean sendEmail) {

        if (ex.getMessage() != null) {
            Logger.e(ex, Html.fromHtml(ex.getMessage()).toString());
        } else {
            Logger.e(ex, "Errore");
        }

        String errorMessage = CommonRESTException.tryRecognizeThenGetMessage(ex);

        if (errorMessage == null) {
            errorMessage = ex.getMessage();

            if (ex.getCause() != null) errorMessage += "<br />" + ex.getCause().getMessage();
        }

        FragmentManager fm = null;

        if (context instanceof FragmentActivity) {
            fm = ((FragmentActivity) context).getSupportFragmentManager();
        } else if (UtilityContext.getMainActivity() != null) {
            fm = UtilityContext.getMainActivity().getSupportFragmentManager();
        }

        if (fm != null) {
            DialogSimpleMessageView.makeErrorDialog(Html.fromHtml(errorMessage), null, null)
                    .show(fm, "tag");
        }

        if (!BuildConfig.DEBUG) {
            if (sendEmail) UtilityLogger.errorMe(ex);
            FirebaseCrashlytics.getInstance().recordException(ex);
        }
    }

}
