package rasel.lunar.launcher.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.annotation.RequiresApi
import com.google.gson.Gson
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.model.NotificationItem
import rasel.lunar.launcher.workers.WorkersDb
import java.security.AccessController.getContext


class NLService : NotificationListenerService() {
    private val TAG: String = this.javaClass.simpleName
    private var nlservicereciver: NLServiceReceiver? = null

    override fun onCreate() {
        super.onCreate()
        nlservicereciver = NLServiceReceiver()
        val filter = IntentFilter()
//        filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE")
        registerReceiver(nlservicereciver, filter)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(nlservicereciver)
    }

    val skips = arrayListOf("com.wssyncmldm")
    @RequiresApi(Build.VERSION_CODES.S)
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        BLog.LOGE( "NLService**********  onNotificationPosted")
        BLog.LOGE("NLServiceID :" + sbn.id + "\t${sbn.notification.tickerText}\t" + sbn.packageName)

        if (sbn.notification.actions != null && sbn.notification.actions.size > 0 && sbn.id > 0 && (sbn.packageName.contains(".") || sbn.packageName.contains("android")) && sbn.packageName.length > 0) {
            NotificationItem().apply {
                notiId = sbn.id
                pkgName = sbn.packageName
                tikerMsg = sbn.notification?.tickerText?.toString() ?: ""
                postTime = sbn.postTime
                uniq_id = "${sbn.id}_${sbn.packageName}"
            }.apply {
                if (skips.contains(pkgName)) {

                } else {
                    WorkersDb.insertNoti(this)
                    BLog.LOGE("NLService**********  onNotificationPosted ${Gson().toJson(this)}")
                }
            }
        }
//        val i = Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE")
//        i.putExtra("notification_event", "onNotificationPosted :" + sbn.packageName + "\n")
//        sendBroadcast(i)
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification) {
        BLog.LOGE( "NLService********** onNOtificationRemoved")
        BLog.LOGE( "NLService ID :" + sbn.id + "\t" + sbn.notification.tickerText + "\t" + sbn.packageName)
        var uniq_id = "${sbn.id}_${sbn.packageName}"
        try {
            WorkersDb.getRealm()?.apply {
                this.writeBlocking {
                    delete(query<NotificationItem>().query("pkgName == $0", sbn.packageName).find())
                }
            }
        }catch (e : Exception){e.printStackTrace()}
//        val i = Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE")
//        i.putExtra("notification_event", "onNotificationRemoved :" + sbn.packageName + "\n")
//        sendBroadcast(i)
    }

    internal inner class NLServiceReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            BLog.LOGE("NLService intent >>> ${intent.action}")
            if (intent.getStringExtra("command") == "clearall") {
                this@NLService.cancelAllNotifications()
            } else if (intent.getStringExtra("command") == "list") {
//                val i1 = Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE")
//                i1.putExtra("notification_event", "=====================")
//                sendBroadcast(i1)
                var i = 1
                for (sbn in this@NLService.activeNotifications) {
                    BLog.LOGE("NLService sbn >>> ${sbn.packageName} , ${Gson().toJson(sbn.notification.extras.keySet())}")
//                    val i2 = Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE")
//                    i2.putExtra("notification_event", i.toString() + " " + sbn.packageName + "\n")
//                    sendBroadcast(i2)
//                    i++
                }
//                val i3 = Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE")
//                i3.putExtra("notification_event", "===== Notification List ====")
//                sendBroadcast(i3)
            }
        }
    }
}