package com.gh.vspace.installexternalgames

import android.app.Application
import android.content.pm.PackageManager
import android.os.Environment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.core.runOnIoThread
import com.gh.vspace.VHelper
import com.lg.vspace.helper.compat.NativeLibraryHelperCompat
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable

class InstallExternalGameViewModel(application: Application) : AndroidViewModel(application) {
    private val _gamesList = MutableLiveData<List<ExternalGameEntity>>(listOf())
    val gamesList: LiveData<List<ExternalGameEntity>> = _gamesList
    private val pkgManger = getApplication<Application>().packageManager
    private var disposable: Disposable = VHelper.callSite.observeOn(AndroidSchedulers.mainThread()).subscribe {
        scanPaths()
    }

    fun scanPaths() {
        runOnIoThread {
            _gamesList.postValue(Environment.getExternalStorageDirectory().walk().maxDepth(1)
                .filter { it.isHidden.not() }
                .filter { it.isFile }
                .onEach {
                    Utils.log(Constants.TAG, "获得文件: ${it.name}")
                }
                .filter { it.extension == "apk" }
                .map {
                    val packageInfo = pkgManger.getPackageArchiveInfo(
                        it.absolutePath,
                        PackageManager.GET_META_DATA or PackageManager.GET_ACTIVITIES
                    )
                    packageInfo?.let { packageInfo ->
                        val applicationInfo = packageInfo.applicationInfo
                        applicationInfo.publicSourceDir = it.absolutePath
                        applicationInfo.sourceDir = it.absolutePath
                        ExternalGameEntity(
                            cpuAbi = NativeLibraryHelperCompat.getPackageAbiList(it.absolutePath),
                            apkPath = it.absolutePath,
                            apkFileName = it.name,
                            apkPackageName = packageInfo.packageName,
                            apkVersion = packageInfo.versionName,
                            appName = pkgManger.getApplicationLabel(applicationInfo).toString(),
                            lastModified = it.lastModified()
                        )
                    }
                }.filterNotNull()
                .toList().sortedByDescending { it.lastModified }
            )
        }
    }


    override fun onCleared() {
        super.onCleared()
        disposable.dispose()
    }

}