KlottrDialog moved to :shared

This commit is contained in:
Olof Hedman
2025-09-24 18:07:33 +02:00
parent 298b73a387
commit e66c1861c2

View File

@@ -0,0 +1,368 @@
package app.klottr
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.decodeToImageBitmap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import app.klottr.events.FoundEvents
import app.klottr.location.LastLocationStore
import app.klottr.location.LocationServiceProvider
import app.klottr.nearby.decideDetailAccess
import app.klottr.net.deleteNote
import app.klottr.net.fetchImageStreamPost
import app.klottr.net.fetchNoteDetail
import app.klottr.platform.AppNavigator
import app.klottr.platform.UiFeedback
import app.klottr.platform.UiFeedbackDuration
import app.klottr.ui.FoundDetailContent
import app.klottr.util.Config
import app.klottr.util.FoundStore
import app.klottr.util.FoundStore.LAYER_KLOTTER
import app.klottr.util.ImageBitmapCache
import app.klottr.util.KLog
import app.klottr.util.NoteDetailCache
import app.klottr.util.buildFoundDetailStrings
import app.klottr.util.formatCoords
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
@Composable
fun KlotterDialog(
id: String,
lat: Double,
lon: Double,
label: String,
currentUserId: Long?,
onClose: () -> Unit
) {
val scope = rememberCoroutineScope()
var askDelete by remember { mutableStateOf(false) }
var deleting by remember { mutableStateOf(false) }
val firstVisitMs = remember(id) {
FoundStore.getFirstVisitMillis(FoundStore.LAYER_KLOTTER, id)
}
val lastVisitMs = remember(id) {
FoundStore.getLastVisitMillis(FoundStore.LAYER_KLOTTER, id)
}
var loading by remember { mutableStateOf(true) }
var text by remember { mutableStateOf(label) }
var titleText by remember { mutableStateOf(label.ifBlank { "Okänt klotter" }) }
// Text för "Skapad: …"
var createdMs by remember { mutableStateOf<Long?>(null) }
var updatedMs by remember { mutableStateOf<Long?>(null) }
var authorName by remember { mutableStateOf<String?>(null) }
var ownerUserId by remember { mutableStateOf<Long?>(null) }
val detailStrings = buildFoundDetailStrings(createdMs, updatedMs, firstVisitMs, lastVisitMs)
val createdText = detailStrings.createdText
val updatedText = detailStrings.updatedText
val firstVisitText = detailStrings.firstVisitText
val lastVisitText = detailStrings.lastVisitText
// Har den här notisen någonsin besökts (oavsett var vi står nu)?
val wasFoundBefore = remember(id) {
FoundStore.getFirstVisitMillis(FoundStore.LAYER_KLOTTER, id) != null
}
var imgBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
var showImageViewer by remember { mutableStateOf(false) }
var prefilledFromCache by remember { mutableStateOf(false) }
// Lager + avstånd (uppdateras när plats-tick sänds)
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
var distanceText by remember { mutableStateOf("-") }
fun recalcDistance() {
val my = LastLocationStore.lastKnownLocation.value
val d = my?.let { app.klottr.util.distanceMeters(it.lat, it.lon, lat, lon).roundToInt() }
distanceText = d?.let { "$it\u00A0m" } ?: "-" // hårt mellanslag
}
// Räkna ut direkt vid öppning
LaunchedEffect(Unit) { recalcDistance() }
val locService = remember { LocationServiceProvider.get() }
DisposableEffect(Unit) {
locService.start()
onDispose { locService.stop() }
}
val currentLocation = locService.location.collectAsState(initial = null)
LaunchedEffect(currentLocation.value?.lat, currentLocation.value?.lon, lat, lon) {
recalcDistance()
}
// Snabb hydrering från cache om vi redan har detalj/bild
LaunchedEffect(id) {
val idL = id.toLongOrNull()
if (idL != null) {
NoteDetailCache.get(idL)?.let { d ->
titleText = d.title.ifBlank { "Okänt klotter" }
text = d.body.ifBlank { titleText }
authorName = d.username
ownerUserId = d.userId
// Formatera skapadtid om den finns (ms → text)
createdMs = d.createdAt
updatedMs = d.updatedAt
val img = d.image
prefilledFromCache = true
loading = false
if (img != null && img.id > 0) {
ImageBitmapCache.get(img.id)?.let { bmp ->
imgBitmap = bmp
}
}
}
}
}
LaunchedEffect(id, lat, lon, label) {
loading = !prefilledFromCache
// Hämta ev. färsk plats
val my = LocationServiceProvider.get().current(highAccuracy = false)
val qLat = my?.lat
val qLon = my?.lon
// --- Delad beslutsregel: ersätter withinRadius/canAttempt/reqLat/reqLon --------------------
val access = decideDetailAccess( // Ny: Beräkna om vi får hämta + vilka coords som ska skickas
wasFoundBefore = wasFoundBefore, // Ny
userLat = qLat, userLon = qLon, // Ny
noteLat = lat, noteLon = lon, // Ny
radiusMeters = Config.DEFAULT_KLOTTER_RADIUS_M // Ny
)
KLog.d { "KlotterDialog canAttempt=${access.canAttempt} wasFoundBefore=$wasFoundBefore" } // Ändrad: Logga via access
// -------------------------------------------------------------------------------------------
if (access.canAttempt) { // Ändrad: Villkor använder delad regel
// get_note.php ska få: Besökt tidigare => NOTISENS coords, annars besökarens (fallback notisens)
// (Nu levererat av access.reqLat/reqLon från delad regel)
val reqLat = access.reqLat // Ny: Koordinater från delad regel
val reqLon = access.reqLon // Ny
val detail = withContext(Dispatchers.IO) {
try {
fetchNoteDetail(id.toLong(), reqLat, reqLon) // Ändrad: Skicka delad regel-coords
} catch (_: Throwable) { null }
}
KLog.d { "detail fetch id=$id ok=${detail != null}" }
if (detail != null) {
// Sätt titel + brödtext från servern
titleText = detail.title.ifBlank { "Okänt klotter" }
text = detail.body.ifBlank { titleText }
authorName = detail.username
ownerUserId = detail.userId
KLog.d {
"KD: ownerUserId=$ownerUserId currentUserId=$currentUserId showDelete=${currentUserId != null && ownerUserId != null && currentUserId == ownerUserId}"
}
// Lagra detalj i cache för snabb öppning nästa gång
runCatching {
NoteDetailCache.put(detail.id, detail)
}
createdMs = detail.createdAt
updatedMs = detail.updatedAt
// Bild: hämta via POST (GDPR-fix), tunga saker i IO — uppdatera UI på huvudtråden.
// TODO: OH: Fix image decoding platform independently
val imgMeta = detail.image
if (imgMeta != null && imgMeta.id > 0) {
// 1) Nätverk + bitmap-dekodning i IO
val bmp = withContext(Dispatchers.IO) {
fetchImageStreamPost(
imageId = imgMeta.id,
noteId = detail.id,
lat = lat,
lon = lon
)?.decodeToImageBitmap()
}
// 2) Tillbaka på huvudtråden: uppdatera UI-tillstånd här
KLog.d { "img POST ok=${bmp != null} id=${imgMeta.id} note=${detail.id}" }
if (bmp != null) {
// bmp är nu en ImageBitmap
imgBitmap = bmp
if (imgMeta.id > 0) {
ImageBitmapCache.put(imgMeta.id, bmp)
}
}
}
} else {
// Kunde inte få detalj – behåll fallback (endast om aldrig funnen och spärr gäller)
if (!wasFoundBefore && access.blockedText != null) { // Ändrad: Använd delad spärrtext
titleText = "Okänt klotter"
text = access.blockedText ?: "Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se det." // Null-säkert: text kräver icke-null
}
}
} else {
// Verkligen okänd och för långt bort
titleText = "Okänt klotter"
text = access.blockedText ?: "Du måste vara inom ${Config.DEFAULT_KLOTTER_RADIUS_M}\u00A0m för att se det." // Ändrad: Delad spärrtext
}
loading = false
}
Dialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.85f) // 85% av skärmens bredd
.clip(RoundedCornerShape(16.dp)),
tonalElevation = 6.dp,
shadowElevation = 6.dp,
color = MaterialTheme.colorScheme.surface
) {
FoundDetailContent(
titleText = titleText,
bodyText = text,
distanceText = distanceText,
wasFoundBefore = wasFoundBefore,
createdText = createdText,
updatedText = updatedText,
authorName = authorName,
showCoords = showCoords,
coordText = if (showCoords) formatCoords(lat, lon) else "",
image = imgBitmap,
onImageClick = { showImageViewer = true }, // Behåll bildvisare på klick
loading = loading,
firstVisitText = firstVisitText,
lastVisitText = lastVisitText,
titleStyle = MaterialTheme.typography.titleLarge.copy( // Ändrad: ge färg
color = MaterialTheme.colorScheme.onSurface
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy( // Ändrad: ge färg
color = MaterialTheme.colorScheme.onSurface
),
captionStyle = MaterialTheme.typography.bodySmall.copy( // Ändrad: ge färg
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Normal
),
// Actions-slot: vi ritar Maps / Radera / Stäng med Android-komponenter
actions = {
val canDelete = currentUserId != null && ownerUserId != null && currentUserId == ownerUserId
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
onClick = {
AppNavigator.openMap(lat, lon, titleText.ifBlank { "Plats" })
}
) { Text("Maps") }
Spacer(Modifier.weight(1f))
if (canDelete) {
Button(
enabled = !deleting,
onClick = { askDelete = true }
) {
if (deleting) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
} else {
Text("Radera")
}
}
}
Button(onClick = onClose) { Text("Stäng") }
}
}
)
}
}
if (showImageViewer && imgBitmap != null) {
//TODO: Use new platform independent ImageViewerDialog
// ImageViewerDialog(bitmap = imgBitmap!!, onClose = { showImageViewer = false })
}
if (askDelete) {
AlertDialog(
onDismissRequest = { if (!deleting) askDelete = false },
title = { Text("Radera klottret?") },
text = { Text("Vill du verkligen radera detta klotter? Det kommer att arkiveras i en vecka för att sedan raderas permanent.") },
confirmButton = {
Button(
enabled = !deleting,
onClick = {
if (deleting) return@Button
val idL = id.toLongOrNull()
if (idL == null) {
UiFeedback.showMessage( "Ogiltigt id.", UiFeedbackDuration.SHORT)
askDelete = false
return@Button
}
deleting = true
scope.launch {
try {
val ok = withContext(Dispatchers.IO) { deleteNote(idL) }
if (ok) {
UiFeedback.showMessage("Klottret raderat.", UiFeedbackDuration.SHORT)
FoundStore.remove(LAYER_KLOTTER, id) // id är din String i KlotterDialog
FoundEvents.notifyFoundUpdated();
askDelete = false
onClose()
} else {
UiFeedback.showMessage("Kunde inte radera (behörighet/nät).", UiFeedbackDuration.SHORT)
}
} finally {
deleting = false
}
}
}
) {
if (deleting) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
} else {
Text("Ja, radera")
}
}
},
dismissButton = {
Button(enabled = !deleting, onClick = { askDelete = false }) {
Text("Avbryt")
}
}
)
}
}