package rasel.lunar.launcher.workers

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.os.Build
import androidx.work.WorkerParameters
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.BuildConfig
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.apps.AppDrawer.Companion.appName
import rasel.lunar.launcher.apps.AppDrawer.Companion.getCategory
import rasel.lunar.launcher.apps.normalize
import rasel.lunar.launcher.model.AppInfo
import rasel.lunar.launcher.utils.AlphabetToChosungMap
import rasel.lunar.launcher.utils.JamoUtils

class AppInfoGetter : BaseGetter {
    companion object {
        val TAG = "AppInfoGetter"
    }
    constructor(context: Context, workerParams: WorkerParameters) : super(context, workerParams) {

    }
    override fun realWork(): Result {
        try {
            var packageManager = lActivity?.packageManager
            var packageInfoList: MutableList<ResolveInfo> = mutableListOf()
            packageInfoList = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                packageManager?.queryIntentActivities(
                    Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER),
                    PackageManager.ResolveInfoFlags.of(0)
                )
            } else {
                (packageManager?.queryIntentActivities(
                    Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER), 0
                ))
            })?.apply {
                removeIf { it.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID) }
                forEach {
                    val result = WorkersDb.getRealm().query<AppInfo>().query("pkgName == $0",it.activityInfo.packageName).find()
                    if (result.size < 1) {
                        val info = AppInfo()
                        info.appName = normalize(appName(it))
                        info.pkgName = it.activityInfo.packageName
                        info.category = getCategory(it.activityInfo.applicationInfo.category)
                        info.alphaCho = AlphabetToChosungMap.getCho(info.appName!!)
                        info.appNameChosung = JamoUtils.split(info.appName).joinToString("")
                        WorkersDb.update(info)
                    } else{
                        val info = WorkersDb.getRealm().copyFromRealm(result.first())
                        info.alphaCho = AlphabetToChosungMap.getCho(info.appName!!)
                        info.appNameChosung = JamoUtils.split(info.appName).joinToString("")
                        WorkersDb.update(info)
                    }
                }
            }!!

        } catch (e : Exception) {e.printStackTrace()}
        return Result.success()
    }
}