package com.example.customtoastview;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    static {
       System.loadLibrary("customtoastview");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Button button = findViewById(R.id.btn_show);
        button.setOnClickListener(v -> {
            showToast("Desain Menyatu!\nBackground icon & body sama.");
        });

        Context context = getApplicationContext();

        if (isHmaDetected(context)){
            Toast.makeText(context , "HMA Detected!", Toast.LENGTH_LONG).show();
        }
    }

    /*public void showCustomToast(Context context, String str) {

        // --- SETTING UTAMA ---
        int iconSize = dpToPx(40);   // Ukuran gambar icon asli
        int iconPadding = dpToPx(8); // Jarak antara gambar icon dengan pinggir lingkaran backgroundnya
        int gapBetweenIconAndText = dpToPx(8);
        int toastColor = Color.parseColor("#FF4747"); // Warna TEMA (Pink)
        int gravityCenter = 17; // Gravity.CENTER
        // ---------------------

        // Hitung ukuran TOTAL lingkaran pembungkus icon
        // (Ukuran Icon + Padding Kiri + Padding Kanan)
        int iconBgSize = iconSize + (iconPadding * 2);

        // 1. ROOT LAYOUT
        RelativeLayout rootLayout = new RelativeLayout(context);
        rootLayout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        rootLayout.setClipChildren(false);
        rootLayout.setClipToPadding(false);

        // Padding atas root = Setengah dari ukuran lingkaran icon
        rootLayout.setPadding(0, iconBgSize / 2, 0, 0);

        // 2. CONTAINER TEXT (BODY TOAST)
        LinearLayout contentContainer = new LinearLayout(context);
        contentContainer.setId(View.generateViewId());
        contentContainer.setOrientation(LinearLayout.VERTICAL);
        contentContainer.setGravity(gravityCenter);

        // Padding atas dinamis: Setengah lingkaran + Jarak
        int dynamicPaddingTop = (iconBgSize / 2) + gapBetweenIconAndText;
        int paddingBottom = dpToPx(16);
        int paddingSide = dpToPx(32);
        contentContainer.setPadding(paddingSide, dynamicPaddingTop, paddingSide, paddingBottom);

        // Background Body (Rounded Rectangle)
        GradientDrawable bodyShape = new GradientDrawable();
        bodyShape.setShape(GradientDrawable.RECTANGLE);
        bodyShape.setColor(toastColor); // WARNA SAMA
        bodyShape.setCornerRadius(dpToPx(24));
        contentContainer.setBackground(bodyShape);

        // Layout Params Body
        RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        containerParams.addRule(14); // RelativeLayout.CENTER_HORIZONTAL
        contentContainer.setLayoutParams(containerParams);

        // 3. TEXTVIEW
        TextView textView = new TextView(context);
        textView.setText(str);
        textView.setTextColor(Color.WHITE);
        textView.setTypeface(null, Typeface.BOLD);
        textView.setGravity(17); // Gravity.CENTER
        textView.setTextSize(2 *//*TypedValue.COMPLEX_UNIT_SP*//*, 14);
        contentContainer.addView(textView);

        rootLayout.addView(contentContainer);

        // 4. ICON WRAPPER (LINGKARAN BACKGROUND ICON)
        FrameLayout iconWrapper = new FrameLayout(context);

        // Background Lingkaran (OVAL)
        GradientDrawable iconBgShape = new GradientDrawable();
        iconBgShape.setShape(GradientDrawable.OVAL);
        iconBgShape.setColor(toastColor); // WARNA SAMA (Kunci agar menyatu)
        // Opsional: Tambah stroke putih biar ada batas tegas (border)
//        iconBgShape.setStroke(dpToPx(4), Color.WHITE);

        iconWrapper.setBackground(iconBgShape);

        // Params Wrapper: Ukuran total lingkaran
        RelativeLayout.LayoutParams wrapperParams = new RelativeLayout.LayoutParams(iconBgSize, iconBgSize);
        wrapperParams.addRule(14); // RelativeLayout.CENTER_HORIZONTAL
        wrapperParams.addRule(6 *//*RelativeLayout.ALIGN_TOP*//*, contentContainer.getId());
        // Tarik ke atas setengah ukuran lingkaran
        wrapperParams.topMargin = -(iconBgSize / 2);
        iconWrapper.setLayoutParams(wrapperParams);

        // 5. IMAGEVIEW (GAMBAR ICON DI DALAM LINGKARAN)
        ImageView iconView = new ImageView(context);
        FrameLayout.LayoutParams iconParams = new FrameLayout.LayoutParams(iconSize, iconSize);
        iconParams.gravity = gravityCenter; // Taruh icon di tengah lingkaran Gravity.CENTER
        iconView.setLayoutParams(iconParams);

        try {
            Drawable appIcon = getPackageManager().getApplicationIcon(getPackageName());
            iconView.setImageDrawable(appIcon);
        } catch (PackageManager.NameNotFoundException ignored) {

        }

        iconWrapper.addView(iconView);
        rootLayout.addView(iconWrapper);

        // 6. SHOW TOAST
        Toast dummyToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        Toast toast = new Toast(context);
        toast.setGravity(dummyToast.getGravity(), dummyToast.getXOffset(), dummyToast.getYOffset());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(rootLayout);
        toast.show();
    }

    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }*/

    public boolean isHmaDetected(Context context) {
        // 1. Ambil data dari API Manager (Yang kemungkinan di-hook/dibohongi)
        AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        List<AccessibilityServiceInfo> apiList = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);

        Set<String> apiServiceNames = new HashSet<>();
        if (apiList != null) {
            for (AccessibilityServiceInfo info : apiList) {
                // Format ID biasanya: com.example.package/.MyAccessibilityService
                apiServiceNames.add(info.getId());
            }
        }

        // 2. Ambil data mentah dari Settings Secure (Seringkali "lupa" di-hook atau sulit diparsing oleh HMA)
        String settingValue = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
        );

        if (settingValue == null || settingValue.isEmpty()) {
            return false; // Tidak ada accessibility service aktif sama sekali
        }

        // Data setting berbentuk string panjang: "com.a/.ServiceA:com.b/.ServiceB"
        String[] rawServices = settingValue.split(":");

        // 3. Bandingkan!
        for (String rawService : rawServices) {
            // Bersihkan nama komponen (kadang ada karakter aneh di setting string)
            String cleanName = rawService.trim();

            if (!cleanName.isEmpty()) {
                // JIKA ada di Settings TAPI tidak ada di API List -> DETECTED!
                if (!apiServiceNames.contains(cleanName)) {
                    Log.e("SecurityCheck", "HMA Detected! Hidden Service found: " + cleanName);
                    return true;
                }
            }
        }

        return false;
    }

    private native void showToast(String str);
}