package ch.threema.app.utils;

import android.app.Activity;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.core.app.NavUtils;
import androidx.core.app.TaskStackBuilder;

import org.slf4j.Logger;

import static ch.threema.base.utils.LoggingKt.getThreemaLogger;

public class NavigationUtil {
    private static final Logger logger = getThreemaLogger("NavigationUtil");

    public static void navigateUpToHome(@NonNull Activity activity) {
        // navigate to home and get rid of the backstack (since we may have pulled the rug from under our feet)
        // use this, if there are intent filters to get to this activity
        Intent upIntent = NavUtils.getParentActivityIntent(activity);
        if (upIntent != null && (activity.shouldUpRecreateTask(upIntent) || activity.isTaskRoot())) {
            TaskStackBuilder.create(activity)
                .addNextIntentWithParentStack(upIntent)
                .startActivities();
        } else {
            try {
                NavUtils.navigateUpFromSameTask(activity);
            } catch (IllegalArgumentException e) {
                logger.info("Missing parent activity entry in manifest for {}", activity.getComponentName());
                logger.error("Exception", e);
            }
        }
    }
}
