package com.cottondb.android import com.cottondb.android.core.CottonCalling import com.cottondb.android.day.todos.TodoRepository import com.cottondb.android.day.notes.NotesJournalRepository import com.cottondb.android.day.notes.NoteEditorModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import com.cottondb.android.day.mood.MoodRepository import com.cottondb.android.day.thoughts.ThoughtRepository import com.cottondb.android.day.calendar.CalendarRepository import com.cottondb.android.day.calendar.CalendarEditorModel import com.cottondb.android.day.goals.GoalsRepository import com.cottondb.android.day.goals.GoalCreationModel import com.cottondb.android.day.goals.GoalDetailModel import com.cottondb.android.day.alarms.Alarm import com.cottondb.android.day.alarms.AlarmEditorModel import com.cottondb.android.day.alarms.AlarmsRepository import com.cottondb.android.capture.CaptureModel import com.cottondb.android.capture.CaptureRepository import com.cottondb.android.capture.CaptureVoice import com.cottondb.android.core.CottonEvent import com.cottondb.android.media.MediaSource import com.cottondb.android.traffic.calls.CallsRepository import com.cottondb.android.traffic.calls.CallHistoryModel import com.cottondb.android.traffic.calls.CallDetailModel import com.cottondb.android.traffic.messages.MessagesRepository import com.cottondb.android.traffic.messages.MessageThreadModel import com.cottondb.android.traffic.messages.MessageSearchModel import com.cottondb.android.traffic.messages.MessageArchiveModel import com.cottondb.android.traffic.messages.ThreadActionsModel import com.cottondb.android.traffic.messages.MessageStarModel import com.cottondb.android.traffic.email.EmailRepository import com.cottondb.android.traffic.email.EmailMailboxModel import com.cottondb.android.traffic.email.EmailDetailModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import java.time.Clock import java.time.LocalDate /** Screen models share one core; no screen creates a native handle or subscribes to it. */ class FeatureModels(private val core: CottonCalling, val clock: Clock, val writerScope: CoroutineScope, val media: MediaSource, private val importStager: com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager, val passwords: PasswordModels, private val searchRecents: com.cottondb.android.search.SearchRecentsStore, private val documentStager: com.cottondb.android.ui.imports.AndroidSafFileStager, val keyboard: com.cottondb.android.keyboard.KeyboardModel? = null) { val takes = TakeModels(core, writerScope, writerScope, android.os.SystemClock::elapsedRealtime, keyboard) val photos = PhotosModels(core, writerScope) val locations = LocationsModels(core, writerScope) val meetings = MeetingsModels(core, writerScope) private var meetingRecordingSession: com.cottondb.android.ui.meetings.recording.MeetingRecordingSession? = null private var meetingsRetired = false private val meetingImports = mutableMapOf() fun meetingRecording(context: android.content.Context, workspaceId: String): com.cottondb.android.ui.meetings.recording.MeetingRecordingSession { check(!meetingsRetired) { "This database is closing." } val existing = meetingRecordingSession if (existing != null) { check(existing.workspaceId == workspaceId) { "The recording belongs to another database." } return existing } return com.cottondb.android.ui.meetings.recording.MeetingRecordingSession(context, workspaceId, core, writerScope, clock) .also { meetingRecordingSession = it } } fun meetingImport(context: android.content.Context, visit: String): com.cottondb.android.ui.work.meetings.MeetingsImportCoordinator { check(!meetingsRetired) { "This database is closing." } return meetingImports.getOrPut(visit) { com.cottondb.android.ui.work.meetings.MeetingsImportCoordinator( com.cottondb.android.ui.work.meetings.meetingsImportStager(context), com.cottondb.android.work.meetings.MeetingCreateRepository(core), writerScope, ) } } fun releaseMeetingImport(visit: String) { val coordinator = meetingImports[visit] ?: return writerScope.launch { coordinator.retire() if (meetingImports[visit] === coordinator) meetingImports.remove(visit) } } /** File receipts settle before the workspace's native handle or model scope closes. */ suspend fun retireMeetings() { meetingsRetired = true kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { meetings.retain(emptyList()) meetingRecordingSession?.retire() meetingImports.values.toList().forEach { it.retire() } meetingImports.clear() meetingRecordingSession = null } } val briefing = BriefingModels(core, writerScope) val activityBin = ActivityBinModels(core, writerScope) val money = MoneyModels(core, clock, clock.zone, writerScope) val memory = MemoryModels(core, writerScope) val reader = ReaderModels(core, writerScope) val documents = DocumentsModels(core, writerScope, media) val documentImport = com.cottondb.android.ui.work.documents.DocumentsImportCoordinator( documentStager, com.cottondb.android.work.documents.DocumentWriteRepository(core), writerScope, ) private var searchModel: com.cottondb.android.search.SearchModel? = null fun search() = searchModel ?: com.cottondb.android.search.SearchModel( com.cottondb.android.search.SearchRepository(core), writerScope, com.cottondb.android.search.CoroutineSearchScheduler(writerScope), searchRecents, ).also { searchModel = it } fun releaseSearch() { searchModel?.close(); searchModel = null } private val settingsPages = mutableMapOf() fun settingsFor(key: String, boot: com.cottondb.android.boot.BootRead) = settingsPages.getOrPut(key) { com.cottondb.android.settings.SettingsModel(core, writerScope, boot) } private val devicePages = mutableMapOf() fun devicesFor(key: String) = devicePages.getOrPut(key) { com.cottondb.android.settings.devices.DevicesModel(com.cottondb.android.settings.devices.DevicesRepository(core)) } private val peopleDirectories = mutableMapOf() private val personPages = mutableMapOf() fun peopleFor(key: String) = peopleDirectories.getOrPut(key) { com.cottondb.android.day.people.PeopleRepository(core) } fun personFor(key: String, id: String) = personPages.getOrPut(key) { com.cottondb.android.day.people.PersonDetailModel(com.cottondb.android.day.people.PeopleRepository(core), id) } private val contactImports = mutableMapOf() fun contactsFor(key: String, source: () -> com.cottondb.android.day.people.ContactsSource) = contactImports.getOrPut(key) { com.cottondb.android.day.people.ContactsImportModel(com.cottondb.android.day.people.ContactsImportRepository(core), source()) } private val projectPages = mutableMapOf() fun projectsFor(key: String, slug: String? = null) = projectPages.getOrPut(key) { val repository = com.cottondb.android.work.projects.ProjectsRepository(core) ProjectPageModels(repository, com.cottondb.android.work.projects.ProjectCreationModel(repository), slug?.let { com.cottondb.android.work.projects.ProjectEditorModel(repository, it) }) } private val mailboxes = mutableMapOf() private val emailReaders = mutableMapOf() fun emailFor(key: String) = mailboxes.getOrPut(key) { EmailMailboxModel(EmailRepository(core)) } fun emailThreadFor(key: String, threadId: String) = emailReaders.getOrPut(key) { EmailDetailModel(threadId, EmailRepository(core)) } private val messageImports = mutableMapOf() fun messageImportFor(key: String) = messageImports.getOrPut(key) { com.cottondb.android.ui.traffic.messages.WhatsAppImportCoordinator( com.cottondb.android.traffic.messages.WhatsAppImportModel( com.cottondb.android.traffic.messages.WhatsAppImportRepository(core)), importStager, writerScope) } private val threadDetails = mutableMapOf() fun threadDetailsFor(key: String, threadId: String) = threadDetails.getOrPut(key) { val repository = com.cottondb.android.traffic.messages.ThreadDetailsRepository(core) ThreadDetailPageModels(repository, com.cottondb.android.traffic.messages.ThreadDetailsMutationModel( com.cottondb.android.traffic.messages.RepositoryThreadDetailActionGateway(repository, threadId)), com.cottondb.android.traffic.messages.ThreadPrivateFieldsModel( com.cottondb.android.traffic.messages.RepositoryThreadPrivateFieldsGateway(repository, threadId))) } private val messagePages = mutableMapOf() fun messagesFor(key: String, threadId: String? = null) = messagePages.getOrPut(key) { val repository = MessagesRepository(core) MessagePageModels(repository, MessageArchiveModel(repository), ThreadActionsModel(repository), MessageSearchModel(repository), MessageStarModel(repository), threadId?.let { MessageThreadModel(repository, it) }) } fun callHistory(personId: String?) = CallHistoryModel(CallsRepository(core), personId) fun callDetail(id: String) = CallDetailModel(CallsRepository(core), id) private val noteEditors = mutableMapOf() private val calendarEditors = mutableMapOf() private val goalCreations = mutableMapOf() private val goalDetails = mutableMapOf() private val goalLists = mutableMapOf() private val captures = mutableMapOf() private val alarmLists = mutableMapOf() private val alarmEditors = mutableMapOf() fun alarmsFor(key: String) = alarmLists.getOrPut(key) { AlarmsRepository(core) } fun alarmEditor(key: String, initial: Alarm?, repository: AlarmsRepository) = alarmEditors.getOrPut(key) { AlarmEditorModel(repository, initial) } fun capture(key: String, voice: () -> CaptureVoice): CaptureModel = captures.getOrPut(key) { CaptureModel(CaptureRepository(core), voice()) } fun releaseCapture(key: String) { captures.remove(key)?.dispose() } fun pauseCapture() { captures.values.forEach { it.dispose() } } fun goals() = GoalsRepository(core) fun goalsFor(key: String) = goalLists.getOrPut(key) { goals() } fun goalCreation(key: String, repository: GoalsRepository) = goalCreations.getOrPut(key) { GoalCreationModel(repository) } fun goalDetail(key: String, id: String) = goalDetails.getOrPut(key) { GoalDetailModel(goals(), id) } fun calendarEditor(key: String, id: String?, occurrenceAt: String?, day: LocalDate, zone: java.time.ZoneId): CalendarEditorModel = calendarEditors.getOrPut(key) { CalendarEditorModel(calendar(), id, occurrenceAt, day, zone) } fun noteEditor(key: String, journalDate: String?, id: String?): NoteEditorModel = noteEditors.getOrPut(key) { NoteEditorModel(notes(), journalDate = journalDate, id = id) } /** Start writes while the process still has foreground time; each retained editor owns its result. */ fun flushNotes() = noteEditors.values.mapNotNull { it.flushPending(writerScope) } fun flushGoals() = goalDetails.values.mapNotNull { it.flushPending(writerScope) } private val _dataRevision = MutableStateFlow(0L) val dataRevision = _dataRevision.asStateFlow() fun handleEvent(event: CottonEvent) { if (event.kind == "data") _dataRevision.value += 1 } val timezone: String get() = clock.zone.id fun today(): LocalDate = LocalDate.now(clock) fun todos(): TodoRepository = TodoRepository(core) fun thoughts(): ThoughtRepository = ThoughtRepository(core) fun mood(): MoodRepository = MoodRepository(core) fun calendar(): CalendarRepository = CalendarRepository(core) fun notes(): NotesJournalRepository = NotesJournalRepository(core) } data class MessagePageModels( val repository: MessagesRepository, val archive: MessageArchiveModel, val actions: ThreadActionsModel, val search: MessageSearchModel, val stars: MessageStarModel, val thread: MessageThreadModel?, ) data class ProjectPageModels( val repository: com.cottondb.android.work.projects.ProjectsRepository, val creation: com.cottondb.android.work.projects.ProjectCreationModel, val editor: com.cottondb.android.work.projects.ProjectEditorModel?, ) data class ThreadDetailPageModels( val repository: com.cottondb.android.traffic.messages.ThreadDetailsRepository, val destructive: com.cottondb.android.traffic.messages.ThreadDetailsMutationModel, val privateFields: com.cottondb.android.traffic.messages.ThreadPrivateFieldsModel, )