package com.cottondb.healthimport android.content.Intentimport android.net.Uriimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.core.content.FileProviderimport com.cottondb.shell.Shellimport com.cottondb.shell.core.CoreExceptionimport com.cottondb.shell.objimport com.cottondb.shell.strimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport java.io.File/** A screen stood on over a place: an answer's own method and request (`health.parameter`, `health.report`, `health.metric`). */dataclassOpened(val method: String, val request: JsonObject)/** What stands over the screen from the foot. */sealedinterfaceSheet {/** Whose report a picked PDF is ([path], copied here): a kept person, or someone new by name. */dataclassWhose(val path: String) : Sheet/** An act's `input` asked before it is sent: one field, or one of its choices; [answer] takes the value, or null. */dataclassInput(val act: JsonObject, val input: JsonObject, val answer: CompletableDeferred<String?>) : Sheet}dataclassToast(val text: String)/** * WHAT HEALTH HOLDS WHILE IT STANDS: the place at the foot, the person whose records are shown, the screens stood on, * the sheet and the toast. Every act the core answers is run here ([run]): its input asked first, then its method; * what comes back is drawn where the core says (a screen, another person, a toast, the PDF). Nothing is decided here, * and no value read is ever logged. */classHealthState(val shell: Shell) {var tab by mutableStateOf(TABS.first())/** The person shown (`person` in every request); null, the owner, as the core takes an absent one. */var person by mutableStateOf<String?>(null)val stack = mutableStateListOf<Opened>()var sheet by mutableStateOf<Sheet?>(null)var toast by mutableStateOf<Toast?>(null)/** Bumped after every act: each screen asks its answer again. */var revision by mutableStateOf(0)/** Add a report's request (`health.addReport`'s act), waiting for the system's file picker. */var picking by mutableStateOf<JsonObject?>(null)/** The confirm an act asks (`{title, body, yes, no}`), its tone, and the answer awaited. */var confirming by mutableStateOf<Triple<JsonObject, String?, CompletableDeferred<Boolean>>?>(null)/** The switcher (`health.people`), asked again with every revision. */var people by mutableStateOf<JsonObject?>(null)fun go(block: suspend () -> Unit) = shell.launch { block() }fun say(text: String?) { if (!text.isNullOrBlank()) toast = Toast(text) }fun back(): Boolean = if (stack.isNotEmpty()) { stack.removeAt(stack.lastIndex); true } elsefalsefun place(next: String) { tab = next; stack.clear() }/** One word of the kit's `health` set. */fun line(key: String): String = shell.lines.line(SET, key)/** A request for one of the person's screens: the person shown and, for Body and Settings, this platform. */fun asking(method: String, extra: JsonObject = JsonObject(emptyMap())): JsonObject = buildJsonObject { person?.let { put("person", it) }if (method == "health.body" || method == "health.settings") put("platform", PLATFORM) extra.forEach { (key, value) -> put(key, value) } }suspendfun ask(method: String, request: JsonObject = JsonObject(emptyMap())): JsonObject? =try { shell.core.obj(method, request) } catch (refused: CoreException) {// The refusal's code alone goes to the log: never a request, which may carry a person or a value. android.util.Log.w(SET, "$method refused: ${refused.code}") say(refused.message); null }suspendfun peopleAgain() { people = ask("health.people", asking("health.people")) }/** * One act the core answered (`{id, label, method, request, input?}`): its input asked first, then sent; what comes * back stands where its method says. */fun run(act: JsonObject) = go {val method = act.str("method") ?: return@goval request = act.obj("request") ?: JsonObject(emptyMap())when (method) {// Another person's records: the screens stand for them."health.labs" -> { person = request.str("person"); stack.clear(); revision++; return@go }"health.parameter", "health.report", "health.metric" -> { stack.add(Opened(method, request)); return@go }// A PDF first, from the system's picker; whose it is after."health.addReport" -> { picking = request; return@go } } act.obj("confirm")?.let { confirm ->val asked = CompletableDeferred<Boolean>() confirming = Triple(confirm, act.str("tone"), asked)val yes = asked.await() confirming = nullif (!yes) return@go }val sent = act.obj("input")?.let { input ->val asked = CompletableDeferred<String?>() sheet = Sheet.Input(act, input, asked)val value = asked.await() sheet = null value ?: return@go buildJsonObject { request.forEach { (k, v) -> put(k, v) }; put(input.str("key") ?: "value", value) } } ?: requestval answer = ask(method, sent) ?: return@go acted(method, sent, answer) }/** What an act's answer asks: a toast, a person to stand on, a PDF to open. */privatesuspendfun acted(method: String, sent: JsonObject, answer: JsonObject) { answer.obj("toast")?.str("text")?.let(::say)if (method == "health.addPerson") answer.str("person")?.let { person = it; stack.clear() }if (method == "health.act" && sent.str("act") == "open_pdf") answer.obj("value")?.let { openPdf(it) }// Sign in and Sign out are this device's own flow (`platform_action: open_flow`), as every app opens them. answer.obj("value")?.takeIf { it.str("platform_action") == "open_flow" }?.str("flow")?.let { shell.flow = it } revision++ }/** The picked PDF copied where the core can read it, then asked whose it is. */suspendfun picked(uri: Uri) {val path = withContext(Dispatchers.IO) { runCatching {val folder = File(shell.context.cacheDir, PICKED).apply { deleteRecursively(); mkdirs() }val file = File(folder, PICKED_NAME) shell.context.contentResolver.openInputStream(uri)?.use { input -> file.outputStream().use { input.copyTo(it) } } ?: error("no stream") file.path }.getOrNull() }if (path == null) { say(line("add.unreadable")); return } sheet = Sheet.Whose(path) }/** `health.addReport` for the person chosen (a kept one's id, or someone new by name): the core keeps and queues the PDF. */fun add(path: String, chosen: String?, newName: String?) = go { sheet = nullval answer = ask("health.addReport", buildJsonObject { put("path", path) chosen?.let { put("person", it) } newName?.let { put("newPerson", it) } put("zone", java.util.TimeZone.getDefault().id) }) ?: return@go answer.obj("toast")?.str("text")?.let(::say) answer.obj("open")?.takeIf { answer.str("report") != null }?.let { open ->// The report stands for its person: their records are the ones shown behind it.val opened = ask(open.str("method").orEmpty(), open.obj("request") ?: JsonObject(emptyMap())) opened?.str("person")?.let { person = it } stack.clear() tab = REPORTS stack.add(Opened(open.str("method").orEmpty(), open.obj("request") ?: JsonObject(emptyMap()))) } revision++ }/** A report's PDF (`{key, contentType}`) from this phone's store, else fetched, opened in the phone's own reader. */privatesuspendfun openPdf(value: JsonObject) {val key = value.str("key") ?: returnval args = buildJsonObject { put("args", buildJsonObject { put("key", key) }) }val path = runCatching { shell.core.obj("read.mediaPath", args).str("path") ?: shell.core.obj("media.ensure", args).str("path") }.getOrNull() ?: run { say(line("reports.no_pdf")); return }val file = withContext(Dispatchers.IO) {val folder = File(shell.context.cacheDir, OPENED).apply { deleteRecursively(); mkdirs() }File(folder, OPENED_NAME).also { File(path).copyTo(it) } }val uri = FileProvider.getUriForFile(shell.context, "${shell.context.packageName}.files", file)val view = Intent(Intent.ACTION_VIEW).setDataAndType(uri, value.str("contentType") ?: PDF) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK) runCatching { shell.context.startActivity(view) }.onFailure { say(line("reports.no_reader")) } }companionobject {/** The four places, in the bar's order (IA.md); their words are the kit's `health.tabs.*`. */val TABS = listOf("labs", "body", "reports", "settings")constval REPORTS = "reports"constval SET = "health"constval PLATFORM = "android"constval PDF = "application/pdf"/** The picked PDF, copied for the core to read (never kept: the core keeps its own copy). */constval PICKED = "health-picked"constval PICKED_NAME = "picked.pdf"/** A report's PDF handed to the phone's reader (app/src/main/res/xml/shared_files.xml `health-report`). */constval OPENED = "health-report"constval OPENED_NAME = "report.pdf" }}