package de.haushalt.app.data

import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import de.haushalt.app.BuildConfig
import okhttp3.Request
import java.io.File

object AppUpdater {
    suspend fun checkUpdate(): AppVersion? {
        val remote = ApiClient.appUpdateApi.getVersion()
        return if (remote.versionCode > BuildConfig.VERSION_CODE) remote else null
    }

    fun downloadAndInstall(context: Context, version: AppVersion) {
        val apkUrl = "${ApiClient.BASE_URL}app/${version.apkFile}"
        val apkFile = File(context.cacheDir, "apk/haushalt.apk")
        apkFile.parentFile?.mkdirs()

        val request = Request.Builder().url(apkUrl).build()
        ApiClient.okHttp.newCall(request).execute().use { response ->
            apkFile.outputStream().use { out ->
                response.body!!.byteStream().copyTo(out)
            }
        }

        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", apkFile)
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "application/vnd.android.package-archive")
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
    }
}
