package com.secspace.lib.common.function.service

import android.accessibilityservice.AccessibilityService
import android.annotation.SuppressLint
import android.content.Context
import android.view.accessibility.AccessibilityEvent
import com.secspace.lib.common.utils.Prefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Created by bxy on 2020-04-01
 */
class EduAccessibilityService : AccessibilityService() {
    private var pkgCache = arrayListOf("EduAccessibilityService")
    private var isWait = false
    private lateinit var context:Context

    @SuppressLint("StringFormatInvalid")
    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        context = this.applicationContext
        val pkg = event.packageName as String
        // 过滤不需要关注的包名
        pkgCache[0] = pkg
        if (isWait) {
            return
        }
        GlobalScope.launch(Dispatchers.IO) {
            while (Prefs.isInSpace(context)) {
                isWait = true
                UseAppManager.getInstance(context).disposePackageName(pkgCache[0])
                delay(60 * 1000)
                isWait = false
            }
        }
    }

    override fun onInterrupt() {}
    override fun onServiceConnected() {
        super.onServiceConnected()
    }

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

    companion object {
        private const val TAG = "EduAccessibilityService"
    }
}