1656 lines
83 KiB
Kotlin
1656 lines
83 KiB
Kotlin
package app.klottr
|
||
|
||
import androidx.compose.animation.AnimatedVisibility
|
||
import androidx.compose.animation.ExperimentalAnimationApi
|
||
import androidx.compose.foundation.BorderStroke
|
||
import androidx.compose.foundation.layout.Arrangement
|
||
import androidx.compose.foundation.layout.Box
|
||
import androidx.compose.foundation.layout.Column
|
||
import androidx.compose.foundation.layout.Row
|
||
import androidx.compose.foundation.layout.Spacer
|
||
import androidx.compose.foundation.layout.consumeWindowInsets
|
||
import androidx.compose.foundation.layout.fillMaxSize
|
||
import androidx.compose.foundation.layout.fillMaxWidth
|
||
import androidx.compose.foundation.layout.height
|
||
import androidx.compose.foundation.layout.padding
|
||
import androidx.compose.foundation.layout.size
|
||
import androidx.compose.foundation.layout.width
|
||
import androidx.compose.foundation.lazy.grid.GridCells
|
||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||
import androidx.compose.foundation.lazy.grid.items
|
||
import androidx.compose.material.icons.Icons
|
||
import androidx.compose.material.icons.filled.Add
|
||
import androidx.compose.material.icons.filled.Bookmark
|
||
import androidx.compose.material.icons.filled.Create
|
||
import androidx.compose.material.icons.filled.Delete
|
||
import androidx.compose.material.icons.filled.Edit
|
||
import androidx.compose.material.icons.filled.Home
|
||
import androidx.compose.material.icons.filled.Info
|
||
import androidx.compose.material.icons.filled.Layers
|
||
import androidx.compose.material.icons.filled.Login
|
||
import androidx.compose.material.icons.filled.Menu
|
||
import androidx.compose.material.icons.filled.Person
|
||
import androidx.compose.material.icons.filled.Place
|
||
import androidx.compose.material.icons.filled.Settings
|
||
import androidx.compose.material3.AlertDialog
|
||
import androidx.compose.material3.AssistChip
|
||
import androidx.compose.material3.Button
|
||
import androidx.compose.material3.ButtonDefaults
|
||
import androidx.compose.material3.Card
|
||
import androidx.compose.material3.CardDefaults
|
||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||
import androidx.compose.material3.FloatingActionButton
|
||
import androidx.compose.material3.HorizontalDivider
|
||
import androidx.compose.material3.Icon
|
||
import androidx.compose.material3.IconButton
|
||
import androidx.compose.material3.MaterialTheme
|
||
import androidx.compose.material3.NavigationBar
|
||
import androidx.compose.material3.NavigationBarItem
|
||
import androidx.compose.material3.OutlinedButton
|
||
import androidx.compose.material3.OutlinedTextField
|
||
import androidx.compose.material3.Scaffold
|
||
import androidx.compose.material3.Switch
|
||
import androidx.compose.material3.Text
|
||
import androidx.compose.material3.TextButton
|
||
import androidx.compose.runtime.Composable
|
||
import androidx.compose.runtime.LaunchedEffect
|
||
import androidx.compose.runtime.collectAsState
|
||
import androidx.compose.runtime.derivedStateOf
|
||
import androidx.compose.runtime.getValue
|
||
import androidx.compose.runtime.mutableStateOf
|
||
import androidx.compose.runtime.remember
|
||
import androidx.compose.runtime.rememberCoroutineScope
|
||
import androidx.compose.runtime.saveable.rememberSaveable
|
||
import androidx.compose.runtime.setValue
|
||
import androidx.compose.ui.Alignment
|
||
import androidx.compose.ui.Modifier
|
||
import androidx.compose.ui.draw.alpha
|
||
import androidx.compose.ui.graphics.decodeToImageBitmap
|
||
import androidx.compose.ui.graphics.vector.ImageVector
|
||
import androidx.compose.ui.text.style.TextAlign
|
||
import androidx.compose.ui.unit.Dp
|
||
import androidx.compose.ui.unit.dp
|
||
import androidx.compose.ui.zIndex
|
||
import app.cash.sqldelight.coroutines.asFlow // SQLDelight coroutine-extensions (Flow-stöd för queries)
|
||
import app.cash.sqldelight.coroutines.mapToList // SQLDelight coroutine-extensions (Flow-stöd för queries)
|
||
import app.klottr.create.CreateNoteOutcome
|
||
import app.klottr.create.QueueOutboxOutcome
|
||
import app.klottr.create.createNoteFlow
|
||
import app.klottr.create.queueNoteDocOutbox
|
||
import app.klottr.events.FoundEvents
|
||
import app.klottr.images.ImageWriter
|
||
import app.klottr.images.ImageReader
|
||
import app.klottr.location.LastLocationStore
|
||
import app.klottr.location.LocationServiceProvider
|
||
import app.klottr.nearby.FoundOpenAction
|
||
import app.klottr.nearby.NearbyBundleShared
|
||
import app.klottr.nearby.OpenFornsok
|
||
import app.klottr.nearby.OpenKlotter
|
||
import app.klottr.nearby.OpenWiki
|
||
import app.klottr.nearby.ScanConfig
|
||
import app.klottr.nearby.enrichKlotterLabels
|
||
import app.klottr.nearby.getNearbyBundle
|
||
import app.klottr.nearby.resolveFoundOpenAction
|
||
import app.klottr.nearby.scanAndMarkFound
|
||
import app.klottr.net.Api
|
||
import app.klottr.net.DigitaltMuseum
|
||
import app.klottr.net.DigitaltMuseumItem
|
||
import app.klottr.net.FornsokShared
|
||
import app.klottr.net.Geocache
|
||
import app.klottr.net.Wikipedia
|
||
import app.klottr.net.createNoteDoc
|
||
import app.klottr.net.fetchImageStreamPost
|
||
import app.klottr.net.fetchMe
|
||
import app.klottr.net.fetchNoteDetail
|
||
import app.klottr.net.setUsernameRemote
|
||
import app.klottr.net.uploadImage
|
||
import app.klottr.platform.AppNavigator
|
||
import app.klottr.platform.OutboxScheduler
|
||
import app.klottr.platform.UiFeedback
|
||
import app.klottr.platform.UiFeedbackDuration
|
||
import app.klottr.platform.hasFgLocationPerms
|
||
import app.klottr.ui.AboutDialog
|
||
import app.klottr.ui.DmDialog
|
||
import app.klottr.ui.FornsokDialog
|
||
import app.klottr.ui.KlottrHomeContent
|
||
import app.klottr.ui.LoginRequiredContent
|
||
import app.klottr.ui.MapContent
|
||
import app.klottr.ui.NearbyContent
|
||
import app.klottr.ui.NearbyDialog
|
||
import app.klottr.ui.NearbyDialogContent
|
||
import app.klottr.ui.UsernameDialog
|
||
import app.klottr.ui.WikiArticleDialog
|
||
import app.klottr.util.AuthShared
|
||
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.OutboxStore
|
||
import app.klottr.util.SettingsStore
|
||
import app.klottr.util.UUID
|
||
import app.klottr.util.formatCoords
|
||
import app.klottr.util.formatDistance
|
||
import kotlinx.coroutines.Dispatchers
|
||
import kotlinx.coroutines.IO
|
||
import kotlinx.coroutines.launch
|
||
import kotlinx.coroutines.withContext
|
||
import kotlin.collections.component1
|
||
import kotlin.collections.component2
|
||
import kotlin.collections.iterator
|
||
import kotlin.collections.orEmpty
|
||
import kotlin.collections.set
|
||
import kotlin.time.Clock
|
||
import kotlin.time.ExperimentalTime
|
||
|
||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalTime::class)
|
||
@Composable
|
||
fun KlottrAppShell(
|
||
onRequestPerms: () -> Unit,
|
||
onLogin: () -> Unit,
|
||
onLogout: () -> Unit
|
||
) {
|
||
val locService = remember { LocationServiceProvider.get() }
|
||
LaunchedEffect(Unit) { locService.start() }
|
||
val currentLoc = locService.location.collectAsState(initial = null)
|
||
val scope = rememberCoroutineScope()
|
||
|
||
// Inloggning
|
||
val loggedIn by AuthShared.loggedIn.collectAsState(initial = false)
|
||
|
||
// Initiera SQLDelight-databasen med hjälp av DatabaseFactory.
|
||
val db = remember {
|
||
val driver = app.klottr.db.DatabaseFactory.createDriver()
|
||
app.klottr.db.KlottrDatabase(driver)
|
||
}
|
||
|
||
// Exponera notes som en State<List<Note>> med Compose-stöd.
|
||
// asFlow() -> gör queryn reaktiv (ström av ändringar).
|
||
// mapToList() -> konverterar varje queryresultat till en lista.
|
||
// collectAsState() -> gör om Flow till Compose-State, så UI ritas om automatiskt.
|
||
val notes by db.notesQueries.all()
|
||
.asFlow()
|
||
.mapToList(Dispatchers.IO)
|
||
.collectAsState(initial = emptyList())
|
||
|
||
|
||
// Settings-state
|
||
// Läser från KMP SettingsStore (no-arg-API). Inga Context-beroenden här längre.
|
||
var onlyNew by remember { mutableStateOf(SettingsStore.getOnlyNewHits()) }
|
||
var satellite by remember { mutableStateOf(SettingsStore.getSatelliteMap()) }
|
||
var night by remember { mutableStateOf(SettingsStore.getNightMode()) }
|
||
var showCoords by remember { mutableStateOf(SettingsStore.getShowCoordinates()) }
|
||
var showKlotter by remember { mutableStateOf(SettingsStore.getShowKlotter()) }
|
||
var showWiki by remember { mutableStateOf(SettingsStore.getShowWikipedia()) }
|
||
var wikiRadius by remember { mutableStateOf(SettingsStore.getWikiRadiusMeters()) }
|
||
var showDm by remember { mutableStateOf(SettingsStore.getShowDigitaltMuseum()) }
|
||
var dmRadius by remember { mutableStateOf(SettingsStore.getDigitaltMuseumRadiusMeters()) }
|
||
var showFornsok by remember { mutableStateOf(SettingsStore.getShowFornsok()) }
|
||
var fornsokRadius by remember { mutableStateOf(SettingsStore.getFornsokRadiusMeters()) }
|
||
var useNewUi by remember { mutableStateOf(SettingsStore.getUseNewUi()) }
|
||
var showAccount by remember { mutableStateOf(false) }
|
||
|
||
|
||
|
||
// UI-state
|
||
var showWrite by remember { mutableStateOf(false) }
|
||
var resetSavingCounter by remember { mutableStateOf(0) }
|
||
var showNearby by remember { mutableStateOf(false) }
|
||
var showMap by remember { mutableStateOf(false) }
|
||
var showSettings by remember { mutableStateOf(false) }
|
||
var locationTick by remember { mutableStateOf(0) }
|
||
var showLoginRequired by remember { mutableStateOf(false) }
|
||
var me by remember { mutableStateOf<app.klottr.net.MeShared?>(null) }
|
||
// Härledd användar-id som uppdateras automatiskt när 'me' ändras
|
||
val currentUserId by remember { derivedStateOf { me?.id } }
|
||
var showUsernameDialog by remember { mutableStateOf(false) }
|
||
|
||
// Nearby-data
|
||
|
||
// Ändrad: Triple -> NearbyBundleShared
|
||
var nearbyBundle by remember {
|
||
mutableStateOf<NearbyBundleShared?>(null)
|
||
}
|
||
|
||
var nearbyLoading by remember { mutableStateOf(false) }
|
||
var nearbyRefreshing by remember { mutableStateOf(false) }
|
||
|
||
var nearbyError by remember { mutableStateOf<String?>(null) }
|
||
var lastKnownLat by remember { mutableStateOf<Double?>(null) }
|
||
var lastKnownLon by remember { mutableStateOf<Double?>(null) }
|
||
|
||
// Klotter-detalj
|
||
var openKlotter by remember {mutableStateOf<OpenKlotter?>(null) }
|
||
// Wiki-detalj
|
||
var openWiki by remember { mutableStateOf<OpenWiki?>(null) }
|
||
// Fornsok-detalj
|
||
var openFornsok by remember { mutableStateOf<OpenFornsok?>(null) }
|
||
// DigitaltMuseum
|
||
var openDm by remember { mutableStateOf<DigitaltMuseumItem?>(null) }
|
||
|
||
|
||
// Hittat-refresh + “force tomt” efter rensning
|
||
var foundRefresh by remember { mutableStateOf(0) }
|
||
var forceEmptyFound by remember { mutableStateOf(false) }
|
||
fun refreshFound() { foundRefresh++ }
|
||
|
||
LaunchedEffect(loggedIn) {
|
||
if (!loggedIn) {
|
||
showUsernameDialog = false
|
||
me = null
|
||
return@LaunchedEffect
|
||
}
|
||
val m = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||
|
||
if (m != null) {
|
||
me = m
|
||
// Visa dialogen ENDAST när vi säkert vet att username saknas
|
||
showUsernameDialog = m.username.isNullOrBlank()
|
||
} else {
|
||
// Okänt läge (nätfel/401 osv) → visa inte dialogen
|
||
showUsernameDialog = false
|
||
}
|
||
}
|
||
|
||
// Kickstarta avstånd direkt vid appstart (via KMP LocationService)
|
||
// Lyssna på KMP LocationService-flöde istället för broadcast
|
||
LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
|
||
currentLoc.value?.let { gp ->
|
||
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||
locationTick++
|
||
}
|
||
}
|
||
|
||
|
||
// 🔴 NYTT: Omedelbar UI-uppdatering när FoundStore ändras
|
||
// Found updates via shared event bus (no broadcasts)
|
||
LaunchedEffect(Unit) {
|
||
FoundEvents.foundUpdated.collect {
|
||
// Trigga omritning varje gång FoundStore uppdateras
|
||
forceEmptyFound = false
|
||
refreshFound()
|
||
}
|
||
}
|
||
|
||
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
||
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
|
||
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp != null) {
|
||
val anyNew = withContext(Dispatchers.IO) {
|
||
scanAndMarkFound(
|
||
lat = gp.lat,
|
||
lon = gp.lon,
|
||
config = ScanConfig(
|
||
showWiki = showWiki,
|
||
wikiRadius = wikiRadius,
|
||
showDm = showDm,
|
||
dmRadius = dmRadius,
|
||
showFornsok = showFornsok,
|
||
fornsokRadius = fornsokRadius
|
||
),
|
||
fetchWiki = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||
fetchDm = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||
fetchFornsok = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) },
|
||
markFound = { layer, id, label, la, lo, now ->
|
||
FoundStore.markFound(layer, id, label, la, lo, now)
|
||
},
|
||
updateAwayFlags = { la, lo ->
|
||
FoundStore.updateAwayFlags(la, lo)
|
||
}
|
||
)
|
||
}
|
||
if (anyNew) {
|
||
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
|
||
refreshFound() // Tvinga omritning av “Senaste”
|
||
/* notify listeners inline: refreshFound() already called */
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
var showAbout by remember { mutableStateOf(false) }
|
||
|
||
Scaffold(
|
||
topBar = {
|
||
CenterAlignedTopAppBar(
|
||
title = { Text("") }, // Standardtitel i appbaren (ingen special-Box, inga extra modifiers)
|
||
actions = { // Dina befintliga actions (Info/Inställningar)
|
||
IconButton(onClick = { showAbout = true }) {
|
||
Icon(imageVector = Icons.Filled.Info, contentDescription = "Om")
|
||
}
|
||
IconButton(onClick = { showSettings = true }) {
|
||
Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar")
|
||
}
|
||
}
|
||
)
|
||
}
|
||
) { padding ->
|
||
if (useNewUi) {
|
||
var selectedTab by rememberSaveable { mutableStateOf("home") }
|
||
var showChangeUsernameDialog by remember { mutableStateOf(false) }
|
||
Scaffold(
|
||
topBar = {
|
||
CenterAlignedTopAppBar(
|
||
title = { Text("") },
|
||
actions = {
|
||
IconButton(onClick = { showAbout = true }) {
|
||
Icon(imageVector = Icons.Filled.Info, contentDescription = "Om")
|
||
}
|
||
IconButton(onClick = { showSettings = true }) {
|
||
Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar")
|
||
}
|
||
}
|
||
)
|
||
},
|
||
bottomBar = {
|
||
NavigationBar {
|
||
NavigationBarItem(
|
||
selected = (selectedTab == "home"),
|
||
onClick = { selectedTab = "home" },
|
||
icon = { Icon(Icons.Filled.Home, contentDescription = "Hem") },
|
||
label = { Text("Hem") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = false,
|
||
onClick = { /* TODO Lager */ },
|
||
icon = { Icon(Icons.Filled.Layers, contentDescription = "Lager") },
|
||
label = { Text("Lager") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = (selectedTab == "nearby"),
|
||
onClick = { selectedTab = "nearby" },
|
||
icon = { Icon(Icons.Filled.Place, contentDescription = "Nära") },
|
||
label = { Text("Nära") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = (selectedTab == "menu"),
|
||
onClick = { selectedTab = "menu" },
|
||
icon = { Icon(Icons.Filled.Menu, contentDescription = "Meny") },
|
||
label = { Text("Meny") }
|
||
)
|
||
}
|
||
},
|
||
floatingActionButton = {
|
||
FloatingActionButton(
|
||
onClick = { showWrite = true }
|
||
) {
|
||
Icon(Icons.Filled.Add, contentDescription = "Klottra")
|
||
}
|
||
},
|
||
floatingActionButtonPosition = androidx.compose.material3.FabPosition.Center,
|
||
content = { innerPadding ->
|
||
if (selectedTab !in listOf("home", "nearby", "menu", "account")) {
|
||
selectedTab = "home"
|
||
}
|
||
// VIKTIGT: vi komponerar ALLA flikar alltid, och växlar bara synlighet.
|
||
// => MapContent förstörs inte när du byter flik, så kartan slipper “blinka”.
|
||
Box(Modifier.fillMaxSize().consumeWindowInsets(innerPadding)) {
|
||
|
||
// === HEM ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "home") 1f else 0f)
|
||
.zIndex(if (selectedTab == "home") 1f else 0f)
|
||
) {
|
||
// Återanvänd gamla layoutens lista med fynd
|
||
val foundList = remember(foundRefresh, forceEmptyFound) {
|
||
if (forceEmptyFound) emptyList() else FoundStore.getAll().reversed()
|
||
}
|
||
val labelOverrides = remember { androidx.compose.runtime.mutableStateMapOf<String, String>() }
|
||
val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" }
|
||
|
||
LaunchedEffect(foundKey) {
|
||
val my = LastLocationStore.lastKnownLocation
|
||
val myLat = my.value?.lat
|
||
val myLon = my.value?.lon
|
||
labelOverrides.clear()
|
||
foundList.forEach { f ->
|
||
if (f.layer == LAYER_KLOTTER) {
|
||
val inside = if (myLat != null && myLon != null)
|
||
app.klottr.util.distanceMeters(myLat, myLon, f.lat, f.lon) <= Config.DEFAULT_KLOTTER_RADIUS_M
|
||
else true
|
||
if (inside) {
|
||
val idL = f.id.toLongOrNull() ?: return@forEach
|
||
if (NoteDetailCache.get(idL) == null) {
|
||
val detail = fetchNoteDetail(idL, f.lat, f.lon)
|
||
if (detail != null) {
|
||
NoteDetailCache.put(idL, detail)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// OBS: INGEN extra padding här — KlottrHomeContent får innerPadding via argumentet nedan.
|
||
KlottrHomeContent(
|
||
contentPadding = innerPadding,
|
||
entries = foundList,
|
||
location = LastLocationStore.lastKnownLocation.collectAsState(),
|
||
showCoords = showCoords,
|
||
labelOverrides = labelOverrides,
|
||
isClickable = { f ->
|
||
(f.layer == FoundStore.LAYER_WIKI) ||
|
||
(f.layer == FoundStore.LAYER_FORNSOK) ||
|
||
(f.layer == FoundStore.LAYER_KLOTTER) ||
|
||
(f.layer == FoundStore.LAYER_DM)
|
||
},
|
||
onEntryClick = { f ->
|
||
scope.launch {
|
||
val action = withContext(Dispatchers.IO) {
|
||
resolveFoundOpenAction(
|
||
entry = f,
|
||
labelOverrides = labelOverrides,
|
||
fornsokAround = { lat, lon, radius ->
|
||
try { FornsokShared.getNearby(lat, lon, radius) } catch (_: Exception) { emptyList() }
|
||
},
|
||
dmLookupByIdentifier = { id ->
|
||
try { app.klottr.net.DigitaltMuseum.lookupByIdentifier(id) } catch (_: Exception) { null }
|
||
}
|
||
)
|
||
}
|
||
when (action) {
|
||
is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label)
|
||
is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon)
|
||
is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item)
|
||
is FoundOpenAction.DigitaltMuseum -> openDm = action.item
|
||
FoundOpenAction.None -> Unit
|
||
}
|
||
}
|
||
},
|
||
isBold = { f -> !FoundStore.isAway(f.layer, f.id) },
|
||
distanceFormatter = ::formatDistance,
|
||
coordsFormatter = ::formatCoords,
|
||
rowTextStyle = MaterialTheme.typography.bodyMedium.copy(
|
||
color = MaterialTheme.colorScheme.onSurface
|
||
),
|
||
header = { /* tom i nya layouten */ },
|
||
footer = { /* tom i nya layouten */ }
|
||
)
|
||
}
|
||
|
||
// === NÄRA ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "nearby") 1f else 0f)
|
||
.zIndex(if (selectedTab == "nearby") 1f else 0f)
|
||
) {
|
||
// Trigga scanning när fliken blir aktiv (och när lager-inställningar ändras)
|
||
LaunchedEffect(selectedTab, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
||
if (selectedTab != "nearby") return@LaunchedEffect
|
||
nearbyRefreshing = true
|
||
nearbyError = null
|
||
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp == null) {
|
||
nearbyLoading = false
|
||
nearbyError = "Ingen plats ännu – prova igen."
|
||
} else {
|
||
lastKnownLat = gp.lat
|
||
lastKnownLon = gp.lon
|
||
|
||
val newBundle = withContext(Dispatchers.IO) {
|
||
getNearbyBundle(
|
||
lat = gp.lat,
|
||
lon = gp.lon,
|
||
showKlotter = showKlotter,
|
||
showWiki = showWiki,
|
||
showDm = showDm,
|
||
showFornsok = showFornsok,
|
||
wikiRadius = wikiRadius,
|
||
dmRadius = dmRadius,
|
||
fornsokRadius = fornsokRadius,
|
||
defaultKlotterRadiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
knownKlotterLabel = { id ->
|
||
FoundStore.getAll()
|
||
.asSequence()
|
||
.filter { it.layer == FoundStore.LAYER_KLOTTER }
|
||
.associate { it.id to it.label }[id]
|
||
},
|
||
klotterFetcher = { la, lo -> Geocache.getNearby(lat = la, lon = lo, radiusMeters = 300, ttlMs = 0L) },
|
||
wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||
dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||
fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) }
|
||
)
|
||
}
|
||
|
||
nearbyBundle = newBundle // uppdatera när klar
|
||
nearbyRefreshing = false
|
||
}
|
||
}
|
||
|
||
// Layout (övre halvan karta, undre halvan lista). Vi ger innerPadding här.
|
||
Column(Modifier.fillMaxSize()) {
|
||
// Övre halvan: karta (ligger kvar i minnet eftersom hela lagret alltid finns)
|
||
Box(modifier = Modifier.weight(1f).fillMaxWidth()) {
|
||
MapContent(
|
||
onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) },
|
||
onOpenUrl = { title, url ->
|
||
when {
|
||
url.contains("wikipedia.org") -> {
|
||
val pageId = url.substringAfter("curid=").toLongOrNull()
|
||
if (pageId != null) {
|
||
openWiki = OpenWiki(pageId, null, null)
|
||
} else {
|
||
AppNavigator.openUrl(url) // fallback
|
||
}
|
||
}
|
||
url.contains("digitaltmuseum.se") -> {
|
||
val match = nearbyBundle?.dm?.firstOrNull {
|
||
it.webUrl == url || it.url == url
|
||
|| url.contains(it.id, ignoreCase = true)
|
||
}
|
||
if (match != null) {
|
||
openDm = match
|
||
} else {
|
||
AppNavigator.openUrl(url)
|
||
}
|
||
}
|
||
url.contains("fornsok") -> {
|
||
val match = nearbyBundle?.forn?.firstOrNull {
|
||
it.uri == url || it.id == url || it.title == url
|
||
|| (it.uri != null && url.contains(it.uri!!, ignoreCase = true))
|
||
}
|
||
if (match != null) {
|
||
openFornsok = OpenFornsok(match)
|
||
} else {
|
||
AppNavigator.openUrl(url)
|
||
}
|
||
}
|
||
else -> AppNavigator.openUrl(url)
|
||
}
|
||
},
|
||
onFornsokClick = { item ->
|
||
openFornsok = OpenFornsok(item)
|
||
},
|
||
isKnownNote = { noteId ->
|
||
FoundStore.getAll().any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() }
|
||
}
|
||
)
|
||
}
|
||
|
||
// Undre halvan: närliggande-listan — visa ALLTID senast cachdade data direkt
|
||
val hasLocOrCache =
|
||
(lastKnownLat != null && lastKnownLon != null) ||
|
||
(nearbyBundle?.entries?.isNotEmpty() == true ||
|
||
nearbyBundle?.dm?.isNotEmpty() == true ||
|
||
nearbyBundle?.forn?.isNotEmpty() == true)
|
||
|
||
Box(modifier = Modifier.weight(1f).fillMaxWidth()) {
|
||
NearbyContent(
|
||
loading = (nearbyBundle == null && nearbyRefreshing),
|
||
error = nearbyError,
|
||
hasLocation = hasLocOrCache, // undvik "Okänt avstånd"-baneret när cache finns
|
||
entries = nearbyBundle?.entries.orEmpty(),
|
||
dm = nearbyBundle?.dm.orEmpty(),
|
||
forn = nearbyBundle?.forn.orEmpty(),
|
||
onOpenAction = { action ->
|
||
when (action) {
|
||
is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label)
|
||
is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon)
|
||
is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item)
|
||
is FoundOpenAction.DigitaltMuseum -> openDm = action.item
|
||
FoundOpenAction.None -> Unit
|
||
}
|
||
},
|
||
rowTextStyle = MaterialTheme.typography.bodyMedium.copy(
|
||
color = MaterialTheme.colorScheme.onSurface
|
||
)
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
// === MENY ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "menu") 1f else 0f)
|
||
.zIndex(if (selectedTab == "menu") 1f else 0f)
|
||
) {
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(innerPadding)
|
||
) {
|
||
Text(
|
||
"Meny",
|
||
style = MaterialTheme.typography.headlineMedium,
|
||
modifier = Modifier.padding(16.dp)
|
||
)
|
||
LazyVerticalGrid(
|
||
columns = GridCells.Fixed(3),
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(8.dp),
|
||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||
) {
|
||
items(
|
||
listOf(
|
||
Triple(Icons.Filled.Settings, "Inställningar") { showSettings = true },
|
||
Triple(Icons.Filled.Info, "Om") { showAbout = true },
|
||
Triple(Icons.Filled.Person, "Konto") { selectedTab = "account" },
|
||
Triple(Icons.Filled.Bookmark, "Bokmärken") { },
|
||
Triple(Icons.Filled.Create, "Mitt klotter") { },
|
||
Triple(
|
||
Icons.Filled.Login,
|
||
if (loggedIn) "Logga ut" else "Logga in"
|
||
) {
|
||
if (loggedIn) onLogout() else onLogin()
|
||
}
|
||
)
|
||
) { (icon, label, action) ->
|
||
MenuTile(icon = icon, label = label, onClick = action)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// === KONTO ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "account") 1f else 0f)
|
||
.zIndex(if (selectedTab == "account") 1f else 0f)
|
||
) {
|
||
AccountScreen(
|
||
me = me,
|
||
onLogin = { onLogin() },
|
||
onLogout = {
|
||
onLogout()
|
||
selectedTab = "menu"
|
||
},
|
||
onDeleteAccount = {
|
||
selectedTab = "menu"
|
||
},
|
||
onChangeUsername = { showChangeUsernameDialog = true },
|
||
modifier = Modifier.padding(innerPadding)
|
||
)
|
||
}
|
||
if (showChangeUsernameDialog) {
|
||
var newName by remember { mutableStateOf("") }
|
||
var errorText by remember { mutableStateOf<String?>(null) }
|
||
var saving by remember { mutableStateOf(false) }
|
||
val scope = rememberCoroutineScope()
|
||
|
||
AlertDialog(
|
||
onDismissRequest = { if (!saving) showChangeUsernameDialog = false },
|
||
title = {
|
||
Column {
|
||
Text("Byt användarnamn", style = MaterialTheme.typography.titleLarge)
|
||
Spacer(Modifier.height(4.dp))
|
||
Text(
|
||
"Efter att du har bytt kan du inte byta igen förrän om tre månader.",
|
||
style = MaterialTheme.typography.bodySmall,
|
||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||
)
|
||
}
|
||
},
|
||
text = {
|
||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
OutlinedTextField(
|
||
value = newName,
|
||
onValueChange = { newName = it; errorText = null },
|
||
label = { Text("Nytt användarnamn") },
|
||
singleLine = true,
|
||
enabled = !saving,
|
||
modifier = Modifier.fillMaxWidth()
|
||
)
|
||
if (errorText != null) {
|
||
Text(errorText!!, color = MaterialTheme.colorScheme.error)
|
||
}
|
||
}
|
||
},
|
||
confirmButton = {
|
||
TextButton(
|
||
enabled = !saving && newName.isNotBlank(),
|
||
onClick = {
|
||
saving = true
|
||
scope.launch {
|
||
val resp = setUsernameRemote(newName)
|
||
if (resp == null) {
|
||
errorText = "Nätverksfel"
|
||
saving = false
|
||
return@launch
|
||
}
|
||
if (resp.ok) {
|
||
// Uppdatera me från servern
|
||
me = withContext(Dispatchers.IO) { fetchMe() }
|
||
showChangeUsernameDialog = false
|
||
saving = false
|
||
} else {
|
||
errorText = when (resp.reason) {
|
||
"invalid" -> "Ogiltigt användarnamn"
|
||
"taken" -> "Användarnamnet är upptaget"
|
||
"reserved" -> "Nyligen använt, reserverat i 6 månader"
|
||
"too_soon" -> "Du måste vänta innan du kan byta igen"
|
||
"already_set" -> "Du har redan ett användarnamn"
|
||
else -> "Fel: ${resp.reason}"
|
||
}
|
||
saving = false
|
||
}
|
||
}
|
||
}
|
||
) {
|
||
Text("Spara")
|
||
}
|
||
},
|
||
dismissButton = {
|
||
TextButton(onClick = { if (!saving) showChangeUsernameDialog = false }) {
|
||
Text("Avbryt")
|
||
}
|
||
}
|
||
)
|
||
}
|
||
}
|
||
}
|
||
)
|
||
} else {
|
||
// --- Nytt: definiera listan + overrides före UI-anropet ---
|
||
val foundList = remember(foundRefresh, forceEmptyFound) {
|
||
if (forceEmptyFound) emptyList() else FoundStore.getAll().reversed()
|
||
}
|
||
val labelOverrides =
|
||
remember { androidx.compose.runtime.mutableStateMapOf<String, String>() }
|
||
val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" }
|
||
|
||
// Förladdning av etiketter/bilder (oförändrad logik, flyttad hit)
|
||
LaunchedEffect(foundKey) {
|
||
val my = LastLocationStore.lastKnownLocation
|
||
val myLat = my.value?.lat
|
||
val myLon = my.value?.lon
|
||
labelOverrides.clear()
|
||
foundList.forEach { f ->
|
||
if (f.layer == LAYER_KLOTTER) {
|
||
val inside = if (myLat != null && myLon != null)
|
||
app.klottr.util.distanceMeters(
|
||
myLat,
|
||
myLon,
|
||
f.lat,
|
||
f.lon
|
||
) <= Config.DEFAULT_KLOTTER_RADIUS_M
|
||
else true
|
||
if (inside) {
|
||
val idL = f.id.toLongOrNull() ?: return@forEach
|
||
if (NoteDetailCache.get(idL) == null) {
|
||
val detail = fetchNoteDetail(idL, f.lat, f.lon)
|
||
if (detail != null) {
|
||
NoteDetailCache.put(idL, detail)
|
||
val img = detail.image
|
||
if (img != null && img.id > 0 && ImageBitmapCache.get(img.id) == null) {
|
||
withContext(Dispatchers.IO) {
|
||
fetchImageStreamPost(
|
||
imageId = img.id,
|
||
noteId = detail.id,
|
||
lat = f.lat,
|
||
lon = f.lon
|
||
)?.decodeToImageBitmap()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
val enriched = withContext(Dispatchers.IO) {
|
||
enrichKlotterLabels(
|
||
found = foundList,
|
||
radiusMeters = 60,
|
||
fetchNearbyKlotter = { la, lo, r ->
|
||
Geocache.getNearby(
|
||
lat = la,
|
||
lon = lo,
|
||
radiusMeters = r,
|
||
ttlMs = 0L
|
||
)
|
||
}
|
||
)
|
||
}
|
||
for ((k, v) in enriched) {
|
||
labelOverrides[k] = v
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- Nytt: KlottrHomeContent (delat mitt-innehåll) ---
|
||
KlottrHomeContent(
|
||
contentPadding = padding,
|
||
entries = foundList,
|
||
location = LastLocationStore.lastKnownLocation.collectAsState(),
|
||
showCoords = showCoords,
|
||
labelOverrides = labelOverrides,
|
||
isClickable = { f ->
|
||
(f.layer == FoundStore.LAYER_WIKI) ||
|
||
(f.layer == FoundStore.LAYER_FORNSOK) ||
|
||
(f.layer == FoundStore.LAYER_KLOTTER) ||
|
||
(f.layer == FoundStore.LAYER_DM)
|
||
},
|
||
onEntryClick = { f ->
|
||
scope.launch {
|
||
val action = withContext(Dispatchers.IO) {
|
||
resolveFoundOpenAction(
|
||
entry = f,
|
||
labelOverrides = labelOverrides,
|
||
fornsokAround = { lat, lon, radius ->
|
||
try {
|
||
FornsokShared.getNearby(lat, lon, radius)
|
||
} catch (_: Exception) {
|
||
emptyList()
|
||
}
|
||
},
|
||
dmLookupByIdentifier = { id ->
|
||
try {
|
||
app.klottr.net.DigitaltMuseum.lookupByIdentifier(id)
|
||
} catch (_: Exception) {
|
||
null
|
||
}
|
||
}
|
||
)
|
||
}
|
||
when (action) {
|
||
is FoundOpenAction.Klotter -> {
|
||
openKlotter = OpenKlotter(
|
||
id = action.id,
|
||
lat = action.lat,
|
||
lon = action.lon,
|
||
label = action.label
|
||
)
|
||
}
|
||
|
||
is FoundOpenAction.Wiki -> {
|
||
openWiki = OpenWiki(action.pageId, action.lat, action.lon)
|
||
}
|
||
|
||
is FoundOpenAction.Fornsok -> {
|
||
openFornsok = OpenFornsok(action.item)
|
||
}
|
||
|
||
is FoundOpenAction.DigitaltMuseum -> {
|
||
openDm = action.item
|
||
}
|
||
|
||
FoundOpenAction.None -> Unit
|
||
}
|
||
}
|
||
},
|
||
isBold = { f -> !FoundStore.isAway(f.layer, f.id) },
|
||
distanceFormatter = ::formatDistance,
|
||
coordsFormatter = ::formatCoords,
|
||
rowTextStyle = MaterialTheme.typography.bodyMedium.copy(
|
||
color = MaterialTheme.colorScheme.onSurface
|
||
),
|
||
header = {
|
||
val hasPerms = hasFgLocationPerms()
|
||
if (!hasPerms) {
|
||
Button(onClick = onRequestPerms) { Text("Begär platstillstånd") }
|
||
}
|
||
|
||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||
Text("Avisera endast nya fynd", modifier = Modifier.weight(1f))
|
||
Switch(
|
||
checked = onlyNew,
|
||
onCheckedChange = {
|
||
onlyNew = it
|
||
SettingsStore.setOnlyNewHits(it)
|
||
}
|
||
)
|
||
}
|
||
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
Button(onClick = {
|
||
if (loggedIn) showWrite = true else showLoginRequired = true
|
||
}) { Text("Klottra") }
|
||
|
||
Button(onClick = {
|
||
nearbyLoading = true
|
||
nearbyError = null
|
||
showNearby = true
|
||
scope.launch {
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp == null) {
|
||
nearbyLoading = false
|
||
nearbyError = "Ingen plats ännu – prova igen."
|
||
return@launch
|
||
}
|
||
lastKnownLat = gp.lat
|
||
lastKnownLon = gp.lon
|
||
|
||
KLog.d { "Närliggande-debug: toggles klotter=$showKlotter wiki=$showWiki dm=$showDm forn=$showFornsok" }
|
||
KLog.d { "Närliggande-debug: loc=${lastKnownLat},${lastKnownLon}" }
|
||
|
||
val bundle = withContext(Dispatchers.IO) {
|
||
getNearbyBundle(
|
||
lat = gp.lat,
|
||
lon = gp.lon,
|
||
showKlotter = showKlotter,
|
||
showWiki = showWiki,
|
||
showDm = showDm,
|
||
showFornsok = showFornsok,
|
||
wikiRadius = wikiRadius,
|
||
dmRadius = dmRadius,
|
||
fornsokRadius = fornsokRadius,
|
||
defaultKlotterRadiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
knownKlotterLabel = { id ->
|
||
FoundStore.getAll()
|
||
.asSequence()
|
||
.filter { it.layer == FoundStore.LAYER_KLOTTER }
|
||
.associate { it.id to it.label }[id]
|
||
},
|
||
klotterFetcher = { la, lo ->
|
||
Geocache.getNearby(
|
||
lat = la,
|
||
lon = lo,
|
||
radiusMeters = 300,
|
||
ttlMs = 0L
|
||
)
|
||
},
|
||
wikiFetcher = { la, lo, r ->
|
||
Wikipedia.getNearby(
|
||
la,
|
||
lo,
|
||
radiusMeters = r
|
||
)
|
||
},
|
||
dmFetcher = { la, lo, r ->
|
||
DigitaltMuseum.getNearby(
|
||
la,
|
||
lo,
|
||
radiusMeters = r
|
||
)
|
||
},
|
||
fornFetcher = { la, lo, r ->
|
||
FornsokShared.getNearby(
|
||
la,
|
||
lo,
|
||
radiusMeters = r
|
||
)
|
||
}
|
||
)
|
||
}
|
||
nearbyBundle = bundle
|
||
|
||
val nowMillis = Clock.System.now().toEpochMilliseconds()
|
||
app.klottr.nearby.markNewFinds(
|
||
entries = bundle.entries, // Använd direkt från bundle
|
||
nowMillis = nowMillis,
|
||
onMarked = { refreshFound() }
|
||
)
|
||
|
||
nearbyLoading = false
|
||
}
|
||
}) { Text("Närliggande") }
|
||
|
||
Button(onClick = { showMap = true }) { Text("Karta") }
|
||
}
|
||
|
||
HorizontalDivider()
|
||
},
|
||
footer = {
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
if (!loggedIn) Button(onClick = onLogin) { Text("Logga in") }
|
||
if (loggedIn) Button(onClick = onLogout) { Text("Logga ut") }
|
||
}
|
||
}
|
||
)
|
||
}
|
||
}
|
||
// Om-appen
|
||
if (showAbout) {
|
||
AboutDialog { showAbout = false }
|
||
}
|
||
// Närliggande
|
||
if (showNearby) {
|
||
NearbyDialog(
|
||
loading = nearbyLoading,
|
||
error = nearbyError,
|
||
lat = lastKnownLat,
|
||
lon = lastKnownLon,
|
||
// Använd namngivna fält från NearbyBundleShared
|
||
entries = nearbyBundle?.entries.orEmpty(), // Ändrad
|
||
dm = nearbyBundle?.dm.orEmpty(), // Ändrad
|
||
forn = nearbyBundle?.forn.orEmpty(), // Ändrad
|
||
|
||
onOpenAction = { action ->
|
||
when (action) {
|
||
is FoundOpenAction.Klotter ->
|
||
openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label)
|
||
is FoundOpenAction.Wiki ->
|
||
openWiki = OpenWiki(action.pageId, action.lat, action.lon)
|
||
is FoundOpenAction.Fornsok ->
|
||
openFornsok = OpenFornsok(action.item)
|
||
is FoundOpenAction.DigitaltMuseum ->
|
||
openDm = action.item
|
||
FoundOpenAction.None -> Unit
|
||
}
|
||
},
|
||
onClose = { showNearby = false }
|
||
)
|
||
}
|
||
|
||
// Karta
|
||
if (showMap) {
|
||
MapDialog(
|
||
onClose = { showMap = false },
|
||
onKlotterClick = { id, la, lo, label ->
|
||
openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label)
|
||
},
|
||
onOpenUrl = { _, url -> AppNavigator.openUrl(url) },
|
||
isKnownNote = { noteId ->
|
||
// Känd = finns i Hittat (FoundStore) → ska alltid visa titel
|
||
FoundStore
|
||
.getAll()
|
||
.any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() }
|
||
}
|
||
)
|
||
}
|
||
|
||
|
||
// Inställningar
|
||
if (showSettings) {
|
||
SettingsDialog(
|
||
onlyNew = onlyNew,
|
||
satellite = satellite,
|
||
night = night,
|
||
showCoords = showCoords,
|
||
|
||
useNewUi = useNewUi,
|
||
onUseNewUiChanged = { SettingsStore.setUseNewUi(it); useNewUi = it },
|
||
|
||
// Sparar via KMP SettingsStore no-arg setters (kompat-overloads med Context är utfasade här).
|
||
onShowCoordsChanged = { SettingsStore.setShowCoordinates(it); showCoords = it },
|
||
showKlotter = showKlotter,
|
||
showWiki = showWiki,
|
||
wikiRadius = wikiRadius,
|
||
showDm = showDm,
|
||
dmRadius = dmRadius,
|
||
showFornsok = showFornsok,
|
||
fornsokRadius = fornsokRadius,
|
||
onOnlyNewChanged = { SettingsStore.setOnlyNewHits(it); onlyNew = it },
|
||
onSatelliteChanged = { SettingsStore.setSatelliteMap(it); satellite = it },
|
||
onNightChanged = { SettingsStore.setNightMode(it); night = it },
|
||
onShowKlotterChanged = { SettingsStore.setShowKlotter(it); showKlotter = it },
|
||
onShowWikiChanged = { SettingsStore.setShowWikipedia(it); showWiki = it },
|
||
onWikiRadiusChanged = { SettingsStore.setWikiRadiusMeters(it); wikiRadius = it },
|
||
onShowDmChanged = { SettingsStore.setShowDigitaltMuseum(it); showDm = it },
|
||
onDmRadiusChanged = { SettingsStore.setDigitaltMuseumRadiusMeters(it); dmRadius = it },
|
||
onShowFornsokChanged = { SettingsStore.setShowFornsok(it); showFornsok = it },
|
||
onFornsokRadiusChanged = { SettingsStore.setFornsokRadiusMeters(it); fornsokRadius = it },
|
||
|
||
onClearFinds = {
|
||
FoundStore.clearAll() // Töm allt
|
||
forceEmptyFound = true // Visa tomt direkt
|
||
refreshFound() // Tvinga omritning
|
||
|
||
// Clear session + notify via shared events (handled in platform location impl)
|
||
FoundStore.clearAll();
|
||
FoundEvents.notifyFoundUpdated()
|
||
// // 1) Nollställ sessions-gates inne i tjänsten
|
||
// context.startService(
|
||
// Intent(context, LocationService::class.java)
|
||
// .setAction(LocationService.ACTION_CLEAR_FOUND_SESSION)
|
||
// )
|
||
//
|
||
// // 2) Pinga UI:t att rita om (nollat läge)
|
||
// context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
||
|
||
// 3) Be tjänsten göra en rescan
|
||
// old Android service call removed (handled in shared layer)
|
||
|
||
// 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad
|
||
// Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten.
|
||
val cfg = ScanConfig(
|
||
showWiki = showWiki,
|
||
wikiRadius = wikiRadius,
|
||
showDm = showDm,
|
||
dmRadius = dmRadius,
|
||
showFornsok = showFornsok,
|
||
fornsokRadius = fornsokRadius
|
||
)
|
||
scope.launch {
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp != null) {
|
||
val anyNew = withContext(Dispatchers.IO) {
|
||
scanAndMarkFound(
|
||
lat = gp.lat, lon = gp.lon,
|
||
config = cfg,
|
||
fetchWiki = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||
fetchDm = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||
fetchFornsok = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) },
|
||
markFound = { layer, id, label, la, lo, now ->
|
||
FoundStore.markFound(layer, id, label, la, lo, now)
|
||
},
|
||
updateAwayFlags = { la, lo ->
|
||
FoundStore.updateAwayFlags(la, lo)
|
||
}
|
||
)
|
||
}
|
||
if (anyNew) {
|
||
forceEmptyFound = false // Tillåt visning igen
|
||
refreshFound() // Rita om “Senaste”
|
||
/* notify listeners inline: refreshFound() already called */
|
||
}
|
||
}
|
||
}
|
||
UiFeedback.showMessage( "Alla fynd rensade.", UiFeedbackDuration.SHORT)
|
||
},
|
||
onClose = { showSettings = false }
|
||
)
|
||
}
|
||
|
||
// Klotter-detalj
|
||
val currentKlotter = openKlotter
|
||
if (currentKlotter != null) {
|
||
KlotterDialog(
|
||
id = currentKlotter.id,
|
||
lat = currentKlotter.lat,
|
||
lon = currentKlotter.lon,
|
||
label = currentKlotter.label,
|
||
currentUserId = currentUserId,
|
||
onClose = { openKlotter = null }
|
||
)
|
||
}
|
||
|
||
// Wiki-detalj
|
||
val currentWiki = openWiki
|
||
if (currentWiki != null) {
|
||
WikiArticleDialog(
|
||
pageId = currentWiki.pageId,
|
||
lat = currentWiki.lat,
|
||
lon = currentWiki.lon,
|
||
onClose = { openWiki = null }
|
||
)
|
||
}
|
||
|
||
// Fornsök-detalj
|
||
val currentForn = openFornsok
|
||
if (currentForn != null) {
|
||
FornsokDialog(
|
||
item = currentForn.item,
|
||
onClose = { openFornsok = null }
|
||
)
|
||
}
|
||
|
||
// DigitaltMuseum-detalj
|
||
val currentDm = openDm
|
||
if (currentDm != null) {
|
||
DmDialog(
|
||
item = currentDm,
|
||
onClose = { openDm = null }
|
||
)
|
||
}
|
||
|
||
|
||
// Skrivdialog (dokument)
|
||
var isSavingDoc by remember { mutableStateOf(false) }
|
||
if (showWrite) {
|
||
// Lagra positionen när man klickat Klottra:
|
||
val initial = LastLocationStore.lastKnownLocation.collectAsState()
|
||
val initialLat = initial.value?.lat
|
||
val initialLon = initial.value?.lon
|
||
|
||
WriteDocDialog(
|
||
onClose = { showWrite = false },
|
||
onSave = { draft, selLat, selLon ->
|
||
if (!loggedIn) {
|
||
UiFeedback.showMessage("Du måste logga in för att kunna klottra.", UiFeedbackDuration.SHORT)
|
||
return@WriteDocDialog
|
||
}
|
||
val created = Clock.System.now().toEpochMilliseconds()
|
||
val requestId = UUID.randomUUID()
|
||
|
||
if (isSavingDoc) return@WriteDocDialog
|
||
isSavingDoc = true
|
||
scope.launch {
|
||
try {
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
// Kör delat online-flöde i IO-tråd
|
||
val outcome = withContext(Dispatchers.IO) {
|
||
createNoteFlow(
|
||
hasImage = draft.image != null,
|
||
uploadImage = {
|
||
// Plattformoberoende läsning via shared ImageReader
|
||
val read = app.klottr.images.ImageReader.read(draft.image!!)
|
||
?: run {
|
||
Api.lastUploadError = "Kunde inte läsa bilddata."
|
||
return@createNoteFlow null
|
||
}
|
||
// 4) ladda upp via commonMain-funktion
|
||
uploadImage(
|
||
data = read.bytes,
|
||
filename = read.filename,
|
||
mime = read.mime,
|
||
lat = selLat,
|
||
lon = selLon
|
||
)
|
||
},
|
||
createNote = { imageId ->
|
||
createNoteDoc(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
imageId = imageId,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
createdAt = created,
|
||
clientRequestId = requestId
|
||
)
|
||
},
|
||
getUploadError = { Api.lastUploadError }
|
||
)
|
||
}
|
||
|
||
when (outcome) {
|
||
is CreateNoteOutcome.Success -> {
|
||
UiFeedback.showMessage("Sparat.")
|
||
|
||
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
||
scope.launch(Dispatchers.IO) {
|
||
try {
|
||
val nearby = Geocache.getNearby(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
radiusMeters = 120,
|
||
ttlMs = 0L
|
||
)
|
||
|
||
// Kandidater nära i både tid och rum (tighta gränser för att undvika felmatch)
|
||
val candidates = nearby.filter {
|
||
app.klottr.util.distanceMeters(selLat, selLon, it.a, it.o) <= 40.0 &&
|
||
kotlin.math.abs(it.c - created) <= 10_000
|
||
}
|
||
val match = candidates.minByOrNull { kotlin.math.abs(it.c - created) }
|
||
|
||
if (match != null) {
|
||
val labelTitle = titleText.ifBlank { match.t ?: "Klotter" } // Spara endast rubriken i “Senaste”
|
||
FoundStore.markFound(
|
||
LAYER_KLOTTER,
|
||
match.i.toString(),
|
||
label = labelTitle,
|
||
lat = match.a,
|
||
lon = match.o,
|
||
timeMillis = Clock.System.now().toEpochMilliseconds()
|
||
)
|
||
withContext(Dispatchers.Main) {
|
||
// TODO: OH: Nog renare om foundstore är ansvarig för att skicka FoundEvents.
|
||
FoundEvents.notifyFoundUpdated()
|
||
}
|
||
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
|
||
// TODO: OH: How to implement? Via foundstore?
|
||
// context.startService(
|
||
// Intent(context, LocationService::class.java)
|
||
// .setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
|
||
// .putExtra("layer", LAYER_KLOTTER)
|
||
// .putExtra("id", match.i.toString())
|
||
// .putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
|
||
// )
|
||
}
|
||
} catch (_: Throwable) { /* no-op */ }
|
||
}
|
||
showWrite = false
|
||
}
|
||
|
||
|
||
is CreateNoteOutcome.UploadFailed -> { // Fallback till offline-utkorg även när bilduppladdning misslyckas
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
val img = draft.image // Ta en snapshot av den valda bilden
|
||
|
||
val queued = withContext(Dispatchers.IO) {
|
||
queueNoteDocOutbox(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
createdAt = created,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
hasImage = (img != null), // Använd snapshotten
|
||
persistImageIfAny = {
|
||
val handle = img ?: return@queueNoteDocOutbox null
|
||
val read = app.klottr.images.ImageReader.read(handle) ?: return@queueNoteDocOutbox null
|
||
val saved = ImageWriter.save(
|
||
read = read,
|
||
subdir = "outbox",
|
||
baseName = "img_${created}"
|
||
) ?: return@queueNoteDocOutbox null
|
||
saved.absolutePath to saved.mime
|
||
},
|
||
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
|
||
OutboxStore.addDoc(
|
||
lat = la,
|
||
lon = lo,
|
||
title = t,
|
||
body = b,
|
||
createdAt = ts,
|
||
radiusM = rad,
|
||
imagePath = imagePath,
|
||
imageMime = imageMime
|
||
)
|
||
},
|
||
scheduleUpload = {
|
||
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||
OutboxScheduler.scheduleUpload();
|
||
// val constraints = Constraints.Builder()
|
||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||
// .build()
|
||
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||
// .setConstraints(constraints).build()
|
||
// WorkManager.getInstance(context).enqueue(req)
|
||
}
|
||
)
|
||
}
|
||
|
||
when (queued) {
|
||
QueueOutboxOutcome.Queued -> {
|
||
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||
showWrite = false
|
||
}
|
||
QueueOutboxOutcome.ImagePersistFailed -> {
|
||
val msg = outcome.message ?: "Bilduppladdning misslyckades."
|
||
UiFeedback.showMessage("$msg\nKunde inte spara bilden lokalt.")
|
||
// Stanna kvar i dialogen
|
||
}
|
||
}
|
||
}
|
||
|
||
is CreateNoteOutcome.CreateFailed -> {
|
||
// Lägg i utkorgen via delad use-case (offline)
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
val img = draft.image // Ta en snapshot av den valda bilden
|
||
|
||
val queued = withContext(Dispatchers.IO) {
|
||
queueNoteDocOutbox(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
createdAt = created,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
hasImage = (img != null), // Använd snapshotten
|
||
persistImageIfAny = {
|
||
val handle = img ?: return@queueNoteDocOutbox null
|
||
val read = ImageReader.read(handle) ?: return@queueNoteDocOutbox null
|
||
val saved = ImageWriter.save(
|
||
read = read,
|
||
subdir = "outbox",
|
||
baseName = "img_${created}"
|
||
) ?: return@queueNoteDocOutbox null
|
||
saved.absolutePath to saved.mime
|
||
},
|
||
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
|
||
OutboxStore.addDoc(
|
||
lat = la,
|
||
lon = lo,
|
||
title = t,
|
||
body = b,
|
||
createdAt = ts,
|
||
radiusM = rad,
|
||
imagePath = imagePath,
|
||
imageMime = imageMime
|
||
)
|
||
},
|
||
scheduleUpload = {
|
||
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||
OutboxScheduler.scheduleUpload()
|
||
// val constraints = Constraints.Builder()
|
||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||
// .build()
|
||
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||
// .setConstraints(constraints).build()
|
||
// WorkManager.getInstance(context).enqueue(req)
|
||
}
|
||
)
|
||
}
|
||
|
||
|
||
when (queued) {
|
||
QueueOutboxOutcome.Queued -> {
|
||
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||
showWrite = false
|
||
}
|
||
QueueOutboxOutcome.ImagePersistFailed -> {
|
||
UiFeedback.showMessage("Kunde inte spara bilden lokalt.")
|
||
// Stanna kvar i dialogen, låt användaren försöka igen eller spara utan bild
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} finally {
|
||
isSavingDoc = false
|
||
}
|
||
}
|
||
},
|
||
initialLat = initialLat,
|
||
initialLon = initialLon,
|
||
resetSavingCounter = resetSavingCounter
|
||
)
|
||
}
|
||
|
||
if (showLoginRequired) {
|
||
AlertDialog(
|
||
onDismissRequest = { showLoginRequired = false },
|
||
title = { Text("Inloggning krävs") },
|
||
text = {
|
||
LoginRequiredContent(
|
||
message = "Du måste logga in för att kunna klottra.",
|
||
textStyle = MaterialTheme.typography.bodyMedium.copy(
|
||
color = MaterialTheme.colorScheme.onSurface // Följer dag/natt
|
||
)
|
||
)
|
||
},
|
||
confirmButton = {
|
||
Button(onClick = {
|
||
showLoginRequired = false
|
||
onLogin() // använder samma onLogin som redan används av “Logga in”-knappen
|
||
}) { Text("Logga in") }
|
||
},
|
||
dismissButton = {
|
||
Button(onClick = { showLoginRequired = false }) {
|
||
Text("Stäng")
|
||
}
|
||
}
|
||
)
|
||
}
|
||
// --- Välj användarnamn (blockerande) ---
|
||
if (showUsernameDialog && loggedIn) {
|
||
UsernameDialog(
|
||
onSaved = { chosen ->
|
||
showUsernameDialog = false
|
||
scope.launch {
|
||
me = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||
}
|
||
// Should be short message.
|
||
UiFeedback.showMessage("Användarnamn satt till ”$chosen”.", UiFeedbackDuration.SHORT)
|
||
},
|
||
onLogout = {
|
||
onLogout() // ← samma onLogout som du redan skickar in till KlottrApp
|
||
}
|
||
)
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun MenuItem(icon: ImageVector, label: String, onClick: () -> Unit) {
|
||
Button(
|
||
onClick = onClick,
|
||
modifier = Modifier.fillMaxWidth().height(64.dp)
|
||
) {
|
||
Row(
|
||
verticalAlignment = Alignment.CenterVertically,
|
||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||
) {
|
||
Icon(icon, contentDescription = label)
|
||
Text(label)
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun MenuTile(icon: ImageVector, label: String, onClick: () -> Unit) {
|
||
Card(
|
||
onClick = onClick,
|
||
modifier = Modifier.size(110.dp),
|
||
shape = MaterialTheme.shapes.medium,
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(12.dp),
|
||
horizontalAlignment = Alignment.CenterHorizontally,
|
||
verticalArrangement = Arrangement.Center
|
||
) {
|
||
Icon(
|
||
icon,
|
||
contentDescription = label,
|
||
modifier = Modifier.size(32.dp),
|
||
tint = MaterialTheme.colorScheme.primary
|
||
)
|
||
Spacer(modifier = Modifier.height(8.dp))
|
||
Text(
|
||
label,
|
||
style = MaterialTheme.typography.bodySmall,
|
||
textAlign = TextAlign.Center
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
fun AccountScreen(
|
||
me: app.klottr.net.MeShared?,
|
||
onLogin: () -> Unit,
|
||
onLogout: () -> Unit,
|
||
onDeleteAccount: () -> Unit,
|
||
onChangeUsername: () -> Unit,
|
||
modifier: Modifier = Modifier
|
||
) {
|
||
Column(
|
||
modifier = modifier
|
||
.fillMaxSize()
|
||
.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||
) {
|
||
Text("Konto", style = MaterialTheme.typography.headlineMedium)
|
||
|
||
Card(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||
) {
|
||
if (me != null) {
|
||
Text("E-post", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||
Text(me.email ?: "-", style = MaterialTheme.typography.bodyLarge)
|
||
|
||
Spacer(Modifier.height(8.dp))
|
||
|
||
Text("Användarnamn", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||
Row(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Text(
|
||
me.username ?: "-",
|
||
style = MaterialTheme.typography.bodyLarge,
|
||
modifier = Modifier.alignByBaseline()
|
||
)
|
||
Spacer(Modifier.weight(1f))
|
||
if (me.canChangeUsername == true) {
|
||
AssistChip(
|
||
onClick = onChangeUsername,
|
||
label = { Text("Byt användarnamn") }, // kortare text gör den ännu smalare
|
||
leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) },
|
||
modifier = Modifier
|
||
.alignByBaseline()
|
||
.height(28.dp) // gör chippen lägre än standard
|
||
)
|
||
}
|
||
}
|
||
|
||
if (me.canChangeUsername == false && me.nextChangeAllowedAt != null) {
|
||
Spacer(Modifier.height(4.dp))
|
||
Text(
|
||
"Du kan byta användarnamn igen tidigast ${me.nextChangeAllowedAt}",
|
||
style = MaterialTheme.typography.bodySmall,
|
||
color = MaterialTheme.colorScheme.error
|
||
)
|
||
}
|
||
|
||
Spacer(Modifier.height(8.dp))
|
||
|
||
Text("Första inloggning", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||
Text(me.firstLogin ?: "-", style = MaterialTheme.typography.bodyLarge)
|
||
} else {
|
||
Text("Ingen användare inloggad.", style = MaterialTheme.typography.bodyLarge)
|
||
}
|
||
}
|
||
}
|
||
|
||
Card(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||
) {
|
||
if (me == null) {
|
||
Button(
|
||
onClick = onLogin,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.buttonColors(
|
||
containerColor = MaterialTheme.colorScheme.primary,
|
||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||
)
|
||
) {
|
||
Icon(Icons.Filled.Login, contentDescription = null)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Logga in")
|
||
}
|
||
} else {
|
||
Button(
|
||
onClick = onLogout,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.buttonColors(
|
||
containerColor = MaterialTheme.colorScheme.primary,
|
||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||
)
|
||
) {
|
||
Icon(Icons.Filled.Login, contentDescription = null)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Logga ut")
|
||
}
|
||
|
||
OutlinedButton(
|
||
onClick = onDeleteAccount,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.outlinedButtonColors(
|
||
contentColor = MaterialTheme.colorScheme.error
|
||
),
|
||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
|
||
) {
|
||
Icon(
|
||
Icons.Filled.Delete,
|
||
contentDescription = null,
|
||
tint = MaterialTheme.colorScheme.error
|
||
)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Radera konto (ej implementerat)")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|