package com.gem.media.splash.base.protocol;

import android.app.NotificationManager;
import android.util.Log;

import com.gem.media.splash.base.utils.ALog;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class NTFMgrHook {

    private static final String TAG = "NTFMgrHook";

    public static void hook() {
        try {
            ALog.d(TAG, "start NTFMgrHook hook");
            Class iNotificationClass = Class.forName("android.app.INotificationManager");
            Field service = NotificationManager.class.getDeclaredField("sService");
            service.setAccessible(true);

            Method getService = NotificationManager.class
                    .getDeclaredMethod("getService");
            getService.setAccessible(true);
            final Object notifyObject = getService.invoke(NotificationManager.class);
            ALog.d(TAG, "notifyObject:" + notifyObject);
            Object proxyNotifyObj = Proxy.newProxyInstance(
                    NotificationManager.class.getClassLoader(),
                    new Class[]{iNotificationClass}, new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args)
                                throws Throwable {
                            try {
                                if ("enqueueNotificationWithTag".equals(method.getName())) {
                                    return null;
                                } else if ("cancelNotificationWithTag".equals(method.getName())) {
                                    return null;
                                }
                            } catch (Throwable e) {
                                ALog.w(TAG, "proxy =" + Log.getStackTraceString(e));
                            }
                            return method.invoke(notifyObject, args);
                        }
                    });
            service.set(NotificationManager.class, proxyNotifyObj);
            ALog.d(TAG, "end NTFMgrHook hook");
        } catch (Throwable e) {
            ALog.w(TAG, e);
        }
    }
}
