package rasel.lunar.launcher.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.model.AppInfo
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.workers.AppInfoGetter
import rasel.lunar.launcher.workers.WorkersDb
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


class PackageEventReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action

        BLog.LOGE("action >>>> ${action}")
        when(action) {
            Intent.ACTION_PACKAGE_ADDED,Intent.ACTION_PACKAGE_INSTALL -> {
                startAppInfoGetter(context)
            }
            Intent.ACTION_PACKAGE_REMOVED -> {
                val packageName = intent.data?.schemeSpecificPart
                if (packageName?.length ?: 0 > 0) {
                    WorkersDb.getRealm().writeBlocking {
                        val result = query<AppInfo>("pkgName == $0", packageName).find()
                        if (result.size == 1) {
                            delete(result)
                        }
                    }
                }
                startAppInfoGetter(context)
            }
            else -> {

            }
        }
    }

    fun startAppInfoGetter(context: Context) {
        var mWorkManager = WorkManager.getInstance(context)
        Executors.newSingleThreadScheduledExecutor().schedule({
            mWorkManager.enqueue(OneTimeWorkRequest.from(AppInfoGetter::class.java))
        }, 5, TimeUnit.SECONDS)
    }
}
