package io.trustbuilder.mfa.android.demoapp.security;

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

import java.io.File;
import java.io.IOException;

public class SecurityUtils {
    private SecurityUtils(){

    }
    public static boolean isDeviceRooted() {
        return isRooted1() || isRooted2() || isRooted3();
    }

    private static boolean isRooted1() {
        String[] paths = {
                "/system/app/Superuser.apk",
                "/sbin/su", "/system/bin/su",
                "/system/xbin/su",
                "/data/local/xbin/su",
                "/data/local/bin/su",
                "/system/sd/xbin/su",
                "/system/bin/failsafe/su",
                "/data/local/su",
                "/su/bin/su"
        };
        for (String path : paths) {
            if (new File(path).exists()) {
                return true;
            }
        }
        return false;
    }

    private static boolean isRooted2() {
        return canExecuteCommand("/system/xbin/which su")
                || canExecuteCommand("su");
    }

    private static boolean isRooted3() {
        String buildTags = android.os.Build.TAGS;
        return buildTags != null && buildTags.contains("test-keys");
    }
    private static boolean canExecuteCommand(String command) {
        try {
            Runtime.getRuntime().exec(command);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static void showAlertDialogAndExitApp(Activity activity, int messageId) {
        AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(activity.getResources().getString(messageId));
        alertDialog.setButton(
                AlertDialog.BUTTON_NEUTRAL,
                "OK",
                (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(intent);
                    activity.finish();
                });

        alertDialog.show();
    }

}
