package xyz.kusoft.argusupdater

import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class ArgusUpdateCacheTest {
    @Test
    fun prepareTargetRemovesFilesFromPreviousUpdates() {
        withTemporaryCache { cacheDirectory, cache ->
            File(cacheDirectory, "old-release.apk").apply {
                parentFile?.mkdirs()
                writeText("old")
            }
            File(cacheDirectory, "new-release.apk.part").writeText("partial")

            val target = cache.prepareTarget()

            assertEquals(ArgusUpdateCache.PACKAGE_FILE_NAME, target.name)
            assertTrue(requireNotNull(target.parentFile).isDirectory)
            assertFalse(File(cacheDirectory, "old-release.apk").exists())
            assertFalse(File(cacheDirectory, "new-release.apk.part").exists())
        }
    }

    @Test
    fun clearRemovesDownloadedAndPartialApks() {
        withTemporaryCache { cacheDirectory, cache ->
            cache.prepareTarget().writeText("downloaded")
            File(cacheDirectory, "${ArgusUpdateCache.PACKAGE_FILE_NAME}.part").writeText("partial")

            cache.clear()

            assertFalse(cacheDirectory.exists())
        }
    }

    private fun withTemporaryCache(block: (File, ArgusUpdateCache) -> Unit) {
        val root = Files.createTempDirectory("aletheia-argus-cache-test").toFile()
        try {
            val cacheDirectory = File(root, ArgusUpdateCache.DIRECTORY_NAME)
            block(cacheDirectory, ArgusUpdateCache(cacheDirectory))
        } finally {
            root.deleteRecursively()
        }
    }
}
