package eu.friedcutlet.yokan.data import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.map /** Narrow port for player-button editing; implementations must keep synchronous commands main-safe. */ interface CustomButtonRepository { fun snapshot(): List fun observeChanges(): Flow fun save(button: DbCustomButton) fun remove(buttonId: Long) fun setFavourite(buttonId: Long) fun move(buttonId: Long, targetIndex: Int) } /** Uses Yokan's synchronous state mirror and queued durable backend, not blocking Room DAO calls. */ class DatabaseCustomButtonRepository( private val database: YokanDatabase, private val clock: () -> Long = ::nowMillis, ) : CustomButtonRepository { override fun snapshot(): List = database.customButtons().sortedBy { it.position } // Notifications let consumers reread current state, so an older queued emission cannot // overwrite a newer value published synchronously after a command. override fun observeChanges(): Flow = database.snapshots() .distinctUntilChangedBy { it.customButtons } .map { } override fun save(button: DbCustomButton) = write { database.upsertCustomButton(button.copy(updatedAt = clock())) } override fun remove(buttonId: Long) = write { database.removeCustomButton(buttonId) } override fun setFavourite(buttonId: Long) = write { val current = snapshot() if (current.none { it.id == buttonId }) return@write val changedAt = clock() current.forEach { button -> val favourite = button.id == buttonId if (button.isFavourite != favourite) { database.upsertCustomButton(button.copy(isFavourite = favourite, updatedAt = changedAt)) } } } override fun move(buttonId: Long, targetIndex: Int) = write { val ordered = snapshot().toMutableList() val index = ordered.indexOfFirst { it.id == buttonId } val target = targetIndex.coerceIn(0, ordered.lastIndex.coerceAtLeast(0)) if (index < 0 || target == index) return@write ordered.add(target, ordered.removeAt(index)) val changedAt = clock() ordered.forEachIndexed { position, button -> if (button.position != position) { database.upsertCustomButton(button.copy(position = position, updatedAt = changedAt)) } } } // Coalesces publication; this contract does not promise rollback on arbitrary exceptions. private fun write(action: () -> Unit) = database.batch(action) }