package com.cottondb.android.ui.photos import android.graphics.Bitmap import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.PhotosModels import com.cottondb.android.ScreenEvidence import com.cottondb.android.FeatureModels import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.design.CottonTheme import com.cottondb.android.media.LocalMedia import com.cottondb.android.media.LocalMediaFile import com.cottondb.android.media.MediaSource import com.cottondb.android.media.EnsuredMedia import com.cottondb.android.media.MediaPathTier import com.cottondb.android.media.ResolvedMediaTier import com.cottondb.android.navigation.Route import java.io.File import java.time.Clock import java.time.Instant import java.time.ZoneOffset import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class PhotosRouteTest { @get:Rule val compose = createComposeRule() private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private var mediaFile: File? = null @After fun close() { compose.runOnIdle { scope.cancel() }; mediaFile?.delete() } @Test fun videosRouteReadsOnceAndOpensTheTypedVideoRouteWithoutEnsure() { val core = Core() val source = bitmapMedia() val models = PhotosModels(core, scope) var opened: Route? = null compose.setContent { CottonTheme { PhotosRoute(Route.Photos("videos"), models, source, CLOCK, 0, {}, { opened = it }) } } compose.waitUntil(5_000) { core.reads == 1 && source.keys.isNotEmpty() } ScreenEvidence.capture("photos-route-videos") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Photo tile video-1: Synthetic video").performClick() assertEquals(Route.VideosVideo("video-1"), opened) assertTrue(source.keys.all { it == "media/poster-1" }) assertTrue(core.methods.all { it == "read.photos" }) } @Test fun remountKeepsTheRetainedFilterAndRefreshesOnlyReadPhotos() { val core = Core() val source = bitmapMedia() val models = PhotosModels(core, scope) val generation = mutableStateOf(0) compose.setContent { CottonTheme { key(generation.value) { PhotosRoute(Route.Photos("photos"), models, source, CLOCK, 0, {}, {}) } } } compose.waitUntil(5_000) { core.reads == 1 } compose.onNodeWithContentDescription("Show videos").performClick() compose.runOnIdle { generation.value++ } compose.waitUntil(5_000) { core.reads == 2 } compose.onNodeWithContentDescription("Photo tile video-1: Synthetic video").assertExists() compose.onNodeWithContentDescription("Photo tile photo-1: Synthetic photo").assertDoesNotExist() assertTrue(core.methods.all { it == "read.photos" }) } @Test fun appNavigationMapsVideosAliasAndBackRetiresTheVisit() { val core = Core() val source = bitmapMedia() val features = features(core, source) compose.setContent { CottonTheme { com.cottondb.android.ui.navigation.AppNavigation( home = com.cottondb.android.home.HomeState.Error("Synthetic Home"), boot = com.cottondb.android.boot.BootRead(true, "joined", null, "synthetic-workspace", null, "Cotton", null), features = features, onJoin = {}, onLeave = {}, onRefreshHome = {}, onSaveArrangement = {}, notificationRoute = Route.Videos, ) } } compose.waitUntil(5_000) { core.reads == 1 && source.keys.contains("media/poster-1") } compose.onNodeWithContentDescription("Photo tile video-1: Synthetic video").assertExists() lateinit var retired: com.cottondb.android.traffic.photos.PhotosLibraryModel compose.runOnIdle { retired = features.photos.library(Route.Photos("videos")) } compose.onNodeWithContentDescription("Back").performClick() compose.waitForIdle() compose.runOnIdle { assertEquals(null, retired.refresh()) } } @Test fun appNavigationAdmitsTheDirectPhotosRoute() { val core = Core() val source = bitmapMedia() val features = features(core, source) compose.setContent { CottonTheme { com.cottondb.android.ui.navigation.AppNavigation( home = com.cottondb.android.home.HomeState.Error("Synthetic Home"), boot = com.cottondb.android.boot.BootRead(true, "joined", null, "synthetic-workspace", null, "Cotton", null), features = features, onJoin = {}, onLeave = {}, onRefreshHome = {}, onSaveArrangement = {}, notificationRoute = Route.Photos(null), ) } } compose.waitUntil(5_000) { core.reads == 1 && source.keys.contains("media/photo-1") } compose.onNodeWithContentDescription("Photo tile photo-1: Synthetic photo").assertExists() assertTrue(core.methods.all { it == "read.photos" }) } private fun features(core: Core, source: MediaSource): FeatureModels { val context = InstrumentationRegistry.getInstrumentation().targetContext val access = com.cottondb.android.passwords.VaultAccess(core) val session = com.cottondb.android.passwords.VaultSession(access, com.cottondb.android.passwords.VaultOperations(access, com.cottondb.android.passwords.VaultKeyRepublisher {}), scope, {}) return FeatureModels(core, CLOCK, scope, source, com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager(context), com.cottondb.android.PasswordModels(core, scope, CLOCK, session) {}, object : com.cottondb.android.search.SearchRecentsStore { override fun load() = emptyList() override fun save(recents: List) = Unit }, com.cottondb.android.ui.imports.AndroidSafFileStager(context, "photos-import-test", "document")) } private fun bitmapMedia(): BitmapMedia { val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "photos-route-synthetic.png") Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888).also { bitmap -> bitmap.eraseColor(android.graphics.Color.rgb(79, 130, 167)) file.outputStream().use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) } bitmap.recycle() } mediaFile = file return BitmapMedia(file) } private class BitmapMedia(private val file: File) : MediaSource { val keys = java.util.concurrent.CopyOnWriteArrayList() override suspend fun local(key: String, tier: MediaPathTier): LocalMedia { keys += key return LocalMedia.Present(LocalMediaFile(file), ResolvedMediaTier.Thumb) } override suspend fun ensure(key: String): EnsuredMedia = error("Photos library never ensures media") override suspend fun viewed(key: String) = false } private class Core : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val methods = mutableListOf(); var reads = 0 override suspend fun call(method: String, request: JsonObject): JsonElement { methods += method; check(request.isEmpty()); reads += 1 return Json.parseToJsonElement("""{"photos":[{"id":"photo-1","key":"media/photo-1","preview":null,"caption":"Synthetic photo","description":null,"takenAt":"2026-09-22T00:00:00Z","sizeBytes":1,"contentType":"image/png","favourite":false,"people":[],"projects":[]}],"videos":[{"id":"video-1","key":"media/video-1","posterKey":"media/poster-1","preview":null,"caption":"Synthetic video","description":null,"takenAt":"2026-09-21T00:00:00Z","sizeBytes":1,"contentType":"video/mp4","favourite":false,"people":[],"projects":[],"durationMs":42000}],"albums":[],"duplicates":0,"faceSuggestions":0}""") } override suspend fun close() = Unit } private companion object { val CLOCK: Clock = Clock.fixed(Instant.parse("2026-09-22T12:00:00Z"), ZoneOffset.UTC) } }