package com.seven.ikar.kotlin.core.update

import android.content.Context
import java.io.File

internal object ArgusAppUpdateCache {
    private const val DOWNLOAD_DIR_NAME = "argus-updater"

    fun buildDownloadTargetFile(context: Context, update: AvailableIkarUpdate): File =
        File(downloadDir(context), update.manifest.release.originalFileName)

    fun deleteStaleDownloads(context: Context, keepFile: File) {
        val keepPath = keepFile.absolutePath
        downloadDir(context).listFiles()
            ?.filter { it.absolutePath != keepPath }
            ?.forEach { it.deleteRecursivelyQuietly() }
    }

    fun deleteAllDownloads(context: Context) {
        downloadDir(context).deleteRecursivelyQuietly()
    }

    private fun downloadDir(context: Context): File =
        File(context.cacheDir, DOWNLOAD_DIR_NAME)

    private fun File.deleteRecursivelyQuietly() {
        if (!exists()) {
            return
        }

        runCatching { deleteRecursively() }
    }
}
