package eu.friedcutlet.yokan.ui.screens.together import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.together.ProfileTogetherSession import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import eu.friedcutlet.yokan.services.together.RoomClient import eu.friedcutlet.yokan.services.together.RoomState import eu.friedcutlet.yokan.services.together.roomMediaFor /** Shared by the title menu: start a room, or add/suggest the title to the current one. */ internal object TogetherActions { /** Creates a room for [manga] and joins it, calling [onRoomOpened] on success; returns the outcome. */ suspend fun startRoom(together: ProfileTogetherSession, http: HttpService, manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, onRoomOpened: () -> Unit): String { val result = together.createAndJoin(http, roomMediaFor(manga, chapter)) ?: return "Log in to your hub under Settings → Sync first." val joined = result.getOrElse { return it.message ?: "Could not create the room." } currentCoroutineContext().ensureActive() if (!together.owns(joined.client)) throw CancellationException("Together room changed before opening it.") val created = joined.created onRoomOpened() return "Room ${created.code} is open. Share the code or ${created.joinUrl}." } fun addToRoom(manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, room: RoomState, client: RoomClient): String { val media = roomMediaFor(manga, chapter) return when { room.canAddToPlaylist -> { client.playlistAdd(media); "Added to the room playlist." } room.canSuggest -> { client.playlistSuggest(media); "Suggested to the host." } else -> "Only the host changes this room's playlist." } } }