package com.miraclegarden.smsmessage.xposed.hook;

import android.app.Notification;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * 银行 App 前台兜底：Hook NotificationManager.notify，从 Notification.extras 取标题/正文。
 */
public final class BankNotificationHook {

    private static final String TAG = "notiMessageHook/BankNotify";

    private BankNotificationHook() {
    }

    public static void install(XC_LoadPackage.LoadPackageParam lpparam, String source) {
        try {
            XposedHelpers.findAndHookMethod(
                    "android.app.NotificationManager",
                    lpparam.classLoader,
                    "notify",
                    String.class,
                    int.class,
                    Notification.class,
                    new NotifyHook(lpparam.packageName, source)
            );
            XposedHelpers.findAndHookMethod(
                    "android.app.NotificationManager",
                    lpparam.classLoader,
                    "notify",
                    int.class,
                    Notification.class,
                    new NotifyHook(lpparam.packageName, source)
            );
            XposedBridge.log(TAG + " installed for " + lpparam.packageName);
        } catch (Throwable t) {
            XposedBridge.log(TAG + " install failed: " + t.getMessage());
        }
    }

    private static final class NotifyHook extends XC_MethodHook {
        private final String packageName;
        private final String source;

        NotifyHook(String packageName, String source) {
            this.packageName = packageName;
            this.source = source;
        }

        @Override
        protected void afterHookedMethod(MethodHookParam param) {
            if (param.args == null || param.args.length == 0) {
                return;
            }
            Notification notification = null;
            for (Object arg : param.args) {
                if (arg instanceof Notification) {
                    notification = (Notification) arg;
                    break;
                }
            }
            if (notification == null) {
                return;
            }
            android.content.Context context = BankHookHelper.getContext();
            if (context == null) {
                return;
            }
            BankHookHelper.forwardFromNotification(context, packageName, notification, source);
        }
    }
}
