package it.integry.integrywmsnative.core.utility;

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

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

import com.annimon.stream.Stream;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.orhanobut.logger.Logger;

import it.integry.integrywmsnative.BuildConfig;
import it.integry.integrywmsnative.core.exception.InvalidConnectionException;
import it.integry.integrywmsnative.core.exception.InvalidLUException;
import it.integry.integrywmsnative.core.exception.InvalidLUGestioneException;
import it.integry.integrywmsnative.core.rest.CommonRESTException;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class UtilityExceptions {

    private static final Class<?>[] FIREBASE_IGNORED_EXCEPTIONS = new Class[] {
            InvalidConnectionException.class,
            InvalidLUGestioneException.class,
            InvalidLUException.class
    };
    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");
        }

        boolean toIgnore = ex.getClass().getName().startsWith("it.integry.integrywmsnative") ||
                Stream.of(FIREBASE_IGNORED_EXCEPTIONS).anyMatch(x -> x.isAssignableFrom(ex.getClass()));

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

}
