package app.furmeet.events.system.schedule.managers

import android.app.Activity
import android.content.Context
import android.content.res.Resources
import org.json.JSONObject
import java.io.InputStream

object RemoteAssetsHolder {
    private const val assetConfig = "out/config.json"
    private lateinit var internalRemoteAssets: RemoteAssets
    fun ensureIsBuilt(activity: Activity) = ensureIsBuilt(activity.baseContext)
    fun ensureIsBuilt(context: Context) = ensureIsBuilt(context.resources)
    fun ensureIsBuilt(resources: Resources) {
        if (!this::internalRemoteAssets.isInitialized)
            resources.assets.open(assetConfig).use { inputStream: InputStream ->
                val inputString = inputStream.bufferedReader(Charsets.UTF_8).readText()
                val inputJSON = JSONObject(inputString)
                internalRemoteAssets = RemoteAssets(
                        inputJSON.getString("server"),
                        inputJSON.getString("project"),
                        inputJSON.getString("siteApp"),
                        inputJSON.getBoolean("preloaded"),
                        inputJSON.getBoolean("onlineApp")
                )
            }
    }
    val remoteAssets get() = internalRemoteAssets
    val remoteAssetsNullable get() = if (this::internalRemoteAssets.isInitialized) internalRemoteAssets else null
}