package com.syaroful.agrilinkvocpro.data.repository

import com.google.android.gms.tasks.Task
import com.google.android.play.core.splitinstall.SplitInstallManager
import com.google.android.play.core.splitinstall.SplitInstallRequest
import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener

class DynamicModuleRepository (
    private val splitInstallManager: SplitInstallManager
) {
    private var sessionId = 0

    fun isModuleDownloaded(moduleName: String): Boolean {
        return splitInstallManager.installedModules.contains(moduleName)
    }

    fun startDownload(
        moduleName: String,
        listener: SplitInstallStateUpdatedListener,
    ): Task<Int> {
        val request = SplitInstallRequest.newBuilder()
            .addModule(moduleName)
            .build()
        splitInstallManager.registerListener(listener)
        return splitInstallManager.startInstall(request)
            .addOnSuccessListener { id -> sessionId = id }
    }

    fun unregisterListener(listener: SplitInstallStateUpdatedListener){
        splitInstallManager.unregisterListener(listener)
    }

    fun getSessionId() = sessionId
}