diff --git a/android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt b/android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt new file mode 100644 index 0000000..c624720 --- /dev/null +++ b/android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt @@ -0,0 +1,1144 @@ +package com.korexlabs.dhinspeccion.ui + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Environment +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.CameraAlt +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Factory +import androidx.compose.material.icons.filled.Inventory2 +import androidx.compose.material.icons.filled.LocationOn +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.WarningAmber +import androidx.compose.material3.Button +import androidx.compose.material3.ElevatedCard +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +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.platform.LocalContext +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.core.content.FileProvider +import androidx.exifinterface.media.ExifInterface +import com.google.android.gms.location.LocationServices +import com.google.android.gms.location.Priority +import com.google.android.gms.tasks.CancellationTokenSource +import com.korexlabs.dhinspeccion.MainViewModel +import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition +import com.korexlabs.dhinspeccion.data.FieldInventoryItem +import com.korexlabs.dhinspeccion.data.FieldType +import com.korexlabs.dhinspeccion.data.VisitDetail +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine +import java.io.File +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +private enum class ModernVisitScreen { OVERVIEW, ACTS, INVENTORY } +private enum class ModernInventoryMode { BROWSE, PICK_PARENT, CREATE_INSTALLATION, CREATE_SUBINSTALLATION } + +private data class ModernGeoSnapshot( + val latitude: Double, + val longitude: Double, + val accuracyM: Double?, +) + +@Composable +fun ModernVisitRoot(model: MainViewModel) { + val visit = model.visit ?: return + var screenName by rememberSaveable(visit.id) { mutableStateOf(ModernVisitScreen.OVERVIEW.name) } + val screen = runCatching { ModernVisitScreen.valueOf(screenName) }.getOrDefault(ModernVisitScreen.OVERVIEW) + + when (screen) { + ModernVisitScreen.OVERVIEW -> ModernVisitOverview( + model = model, + onActs = { screenName = ModernVisitScreen.ACTS.name }, + onInventory = { screenName = ModernVisitScreen.INVENTORY.name }, + ) + ModernVisitScreen.ACTS -> ModernMobileActsScreen( + model = model, + onBack = { screenName = ModernVisitScreen.OVERVIEW.name }, + onGoInventory = { screenName = ModernVisitScreen.INVENTORY.name }, + ) + ModernVisitScreen.INVENTORY -> ModernFieldInventoryScreen( + model = model, + onBack = { screenName = ModernVisitScreen.ACTS.name }, + ) + } +} + +@Composable +private fun ModernVisitOverview( + model: MainViewModel, + onActs: () -> Unit, + onInventory: () -> Unit, +) { + val visit = model.visit ?: return + Column( + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 18.dp, vertical = 20.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + ModernHeader( + title = "Inspección en campo", + subtitle = visit.code, + onBack = { model.closeVisitView() }, + ) + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large, + tonalElevation = 1.dp, + ) { + Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text( + visit.scopeAsset?.name ?: "Yacimiento", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + modifier = Modifier.weight(1f), + ) + StatusPill(modernStatusLabel(visit.status)) + } + visit.operatorCompany?.name?.takeIf { it.isNotBlank() }?.let { + Text(it, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + visit.operationalArea?.name?.takeIf { it.isNotBlank() }?.let { + Text("Área · $it", style = MaterialTheme.typography.bodyMedium) + } + visit.plannedStartAt?.let { + Text("Planificada · ${modernShortDate(it)}", style = MaterialTheme.typography.bodySmall) + } + } + } + + ModernMessage(model) + + visit.instructions?.takeIf { it.isNotBlank() }?.let { + ElevatedCard(Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("Instrucciones", fontWeight = FontWeight.Bold) + Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + + if (visit.status == "PLANNED") { + ElevatedCard(Modifier.fillMaxWidth()) { + Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("Listo para iniciar", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text( + "Al iniciar se habilitan Actas, Hallazgos y el Inventario de campo.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button( + onClick = { model.startVisit(); onActs() }, + enabled = !model.busy, + modifier = Modifier.fillMaxWidth(), + ) { Text(if (model.busy) "Iniciando…" else "Iniciar inspección") } + } + } + } + + if (visit.status == "IN_PROGRESS") { + Text("Acciones de campo", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + ElevatedCard(onClick = onActs, modifier = Modifier.fillMaxWidth()) { + Row( + Modifier.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Surface(shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.primaryContainer) { + Icon(Icons.Filled.Inventory2, null, Modifier.padding(11.dp), tint = MaterialTheme.colorScheme.primary) + } + Column(Modifier.weight(1f)) { + Text("Actas y Hallazgos", fontWeight = FontWeight.Bold) + val drafts = model.acts.count { it.status == "DRAFT" } + Text( + "${model.acts.size} Acta${if (model.acts.size == 1) "" else "s"}${if (drafts > 0) " · $drafts en borrador" else ""}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + ElevatedCard(onClick = onInventory, modifier = Modifier.fillMaxWidth()) { + Row( + Modifier.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Surface(shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.secondaryContainer) { + Icon(Icons.Filled.Factory, null, Modifier.padding(11.dp), tint = MaterialTheme.colorScheme.secondary) + } + Column(Modifier.weight(1f)) { + Text("Inventario de campo", fontWeight = FontWeight.Bold) + Text( + "Buscar existente o cargar Instalación / Subinstalación", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } else if (visit.status == "CLOSED") { + OutlinedButton(onClick = onActs, modifier = Modifier.fillMaxWidth()) { Text("Ver Actas") } + } + + ModernChecklistCard(visit) + + if (visit.planningAssets.any { it.included }) { + Text("Inventario planificado", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + visit.planningAssets.filter { it.included }.take(8).forEach { asset -> + Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, tonalElevation = 1.dp) { + Column(Modifier.padding(14.dp)) { + Text(asset.name, fontWeight = FontWeight.SemiBold) + Text("${asset.code} · ${asset.typeName.orEmpty()}", style = MaterialTheme.typography.bodySmall) + } + } + } + } + Spacer(Modifier.height(24.dp)) + } +} + +@Composable +private fun ModernChecklistCard(visit: VisitDetail) { + val checklist = visit.checklist + ElevatedCard(Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("Antecedentes", fontWeight = FontWeight.Bold) + Text( + "${checklist.antecedents} antecedentes · ${checklist.upcomingControls} próximos controles", + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (checklist.companyOverdue > 0 || checklist.verificationOverdue > 0) { + Text( + "Vencidos: empresa ${checklist.companyOverdue} · verificaciones ${checklist.verificationOverdue}", + color = MaterialTheme.colorScheme.error, + ) + } + if (checklist.stale) { + Text("El checklist requiere actualización.", color = MaterialTheme.colorScheme.error) + } + } + } +} + +@Composable +private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val focusManager = LocalFocusManager.current + val keyboard = LocalSoftwareKeyboardController.current + val visit = model.visit ?: return + + var modeName by rememberSaveable(visit.id) { mutableStateOf(ModernInventoryMode.BROWSE.name) } + val mode = runCatching { ModernInventoryMode.valueOf(modeName) }.getOrDefault(ModernInventoryMode.BROWSE) + var search by rememberSaveable(visit.id) { mutableStateOf("") } + var parentSearch by rememberSaveable(visit.id) { mutableStateOf("") } + var parentId by rememberSaveable(visit.id) { mutableStateOf(null) } + var parentLabel by rememberSaveable(visit.id) { mutableStateOf("") } + var name by rememberSaveable(visit.id) { mutableStateOf("") } + var commonName by rememberSaveable(visit.id) { mutableStateOf("") } + var selectedTypeId by rememberSaveable(visit.id) { mutableStateOf(null) } + var selectedFamilyId by rememberSaveable(visit.id) { mutableStateOf(null) } + var familySearch by rememberSaveable(visit.id) { mutableStateOf("") } + val attributeValues = remember { mutableStateMapOf() } + var pendingAutoPhoto by rememberSaveable(visit.id) { mutableStateOf(false) } + var localError by rememberSaveable(visit.id) { mutableStateOf(null) } + var permissionAction by rememberSaveable(visit.id) { mutableStateOf("PHOTO") } + + var mergeSearch by rememberSaveable(visit.id) { mutableStateOf("") } + var mergeCandidateId by rememberSaveable(visit.id) { mutableStateOf(null) } + var mergeReason by rememberSaveable(visit.id) { mutableStateOf("") } + + fun resetForm() { + name = "" + commonName = "" + selectedTypeId = null + selectedFamilyId = null + familySearch = "" + attributeValues.clear() + localError = null + } + + fun backToBrowse() { + modeName = ModernInventoryMode.BROWSE.name + parentId = null + parentLabel = "" + parentSearch = "" + resetForm() + model.loadFieldTypes(null) + } + + fun startInstallation() { + model.clearSelectedFieldAsset() + modeName = ModernInventoryMode.CREATE_INSTALLATION.name + parentId = null + parentLabel = visit.scopeAsset?.name ?: "Yacimiento de la inspección" + resetForm() + model.loadFieldTypes(null) + } + + fun startSubinstallation() { + model.clearSelectedFieldAsset() + modeName = ModernInventoryMode.PICK_PARENT.name + parentId = null + parentLabel = "" + parentSearch = "" + resetForm() + model.searchInventory("", visit.scopeAsset?.id) + } + + fun chooseParent(item: FieldInventoryItem) { + keyboard?.hide() + focusManager.clearFocus() + parentId = item.id + parentLabel = "${item.name} · ${item.code}" + modeName = ModernInventoryMode.CREATE_SUBINSTALLATION.name + resetForm() + model.loadFieldTypes(item.id) + } + + LaunchedEffect(visit.id) { + model.searchInventory("", visit.scopeAsset?.id) + } + + LaunchedEffect(modeName, parentSearch) { + if (mode == ModernInventoryMode.PICK_PARENT) { + delay(280) + model.searchInventory(parentSearch.trim(), visit.scopeAsset?.id) + } + } + + LaunchedEffect(modeName, search) { + if (mode == ModernInventoryMode.BROWSE) { + delay(320) + model.searchInventory(search.trim()) + } + } + + LaunchedEffect(model.fieldTypes, modeName) { + if (mode == ModernInventoryMode.CREATE_INSTALLATION || mode == ModernInventoryMode.CREATE_SUBINSTALLATION) { + val preferred = model.fieldTypes.firstOrNull { type -> + val normalized = modernNormalize(type.structuralKind ?: type.code.ifBlank { type.name }) + when (mode) { + ModernInventoryMode.CREATE_INSTALLATION -> normalized.contains("instalacion") && !normalized.contains("subinstalacion") + ModernInventoryMode.CREATE_SUBINSTALLATION -> normalized.contains("subinstalacion") + else -> false + } + } ?: model.fieldTypes.firstOrNull() + if (model.fieldTypes.none { it.id == selectedTypeId }) { + selectedTypeId = preferred?.id + selectedFamilyId = null + familySearch = "" + attributeValues.clear() + } + } + } + + val selectedType = model.fieldTypes.firstOrNull { it.id == selectedTypeId } + val selectedFamily = selectedType?.families?.firstOrNull { it.id == selectedFamilyId } + val filteredFamilies = remember(selectedType, familySearch) { + val needle = modernNormalize(familySearch) + selectedType?.families.orEmpty().filter { family -> + needle.isBlank() || modernNormalize("${family.code} ${family.name}").contains(needle) + } + } + + var pendingPhotoFile by remember { mutableStateOf(null) } + var pendingPhotoGeo by remember { mutableStateOf(null) } + + val takePicture = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success -> + val file = pendingPhotoFile + val geo = pendingPhotoGeo + if (success && file != null && geo != null) { + runCatching { writeModernExif(file, geo) } + model.uploadFieldPhoto(file, geo.latitude, geo.longitude, geo.accuracyM) + } else if (!success) { + localError = "La foto quedó pendiente. Podés tomarla cuando estés listo." + } + pendingPhotoFile = null + pendingPhotoGeo = null + } + + val beginPhoto: () -> Unit = { + scope.launch { + runCatching { currentModernGeo(context) } + .onSuccess { geo -> + val (file, uri) = newModernPhoto(context) + pendingPhotoFile = file + pendingPhotoGeo = geo + takePicture.launch(uri) + } + .onFailure { localError = it.message ?: "No se pudo obtener el GPS para la fotografía." } + } + } + + fun createWithLocation() { + val type = selectedType ?: return + val effectiveParent = if (mode == ModernInventoryMode.CREATE_SUBINSTALLATION) parentId else null + scope.launch { + runCatching { currentModernGeo(context) } + .onSuccess { geo -> + pendingAutoPhoto = true + model.createFieldAsset( + type = type, + parentId = effectiveParent, + familyId = selectedFamilyId, + name = name, + commonName = commonName, + attributes = buildModernAttributes(type, attributeValues), + latitude = geo.latitude, + longitude = geo.longitude, + accuracyM = geo.accuracyM, + ) + } + .onFailure { localError = it.message ?: "No se pudo capturar la ubicación GPS." } + } + } + + val permissionsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> + val cameraAllowed = result[Manifest.permission.CAMERA] == true || modernHasPermission(context, Manifest.permission.CAMERA) + val locationAllowed = result[Manifest.permission.ACCESS_FINE_LOCATION] == true || + result[Manifest.permission.ACCESS_COARSE_LOCATION] == true || modernHasLocation(context) + if (permissionAction == "CREATE") { + if (cameraAllowed && locationAllowed) createWithLocation() + else localError = "Para el alta rápida se necesitan cámara y ubicación." + } else { + if (cameraAllowed && locationAllowed) beginPhoto() + else localError = "Para completar el alta se necesitan cámara y ubicación." + } + } + + fun requestCreate() { + permissionAction = "CREATE" + if (modernHasPermission(context, Manifest.permission.CAMERA) && modernHasLocation(context)) { + createWithLocation() + } else { + permissionsLauncher.launch( + arrayOf( + Manifest.permission.CAMERA, + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION, + ), + ) + } + } + + fun requestPhoto() { + permissionAction = "PHOTO" + if (modernHasPermission(context, Manifest.permission.CAMERA) && modernHasLocation(context)) { + beginPhoto() + } else { + permissionsLauncher.launch( + arrayOf( + Manifest.permission.CAMERA, + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION, + ), + ) + } + } + + val selectedCapture = model.selectedFieldAsset + LaunchedEffect(selectedCapture?.asset?.id, pendingAutoPhoto) { + val capture = selectedCapture?.capture + if (pendingAutoPhoto && capture?.captureRequired == true && capture.creationGpsCaptured && capture.fieldPhotoCount == 0) { + pendingAutoPhoto = false + requestPhoto() + } + } + + val mergeSource = selectedCapture?.takeIf { + it.capture.captureRequired && modernItemTypeCode(it.asset) in setOf("instalacion", "subinstalacion") + } + val mergeCandidates = remember(model.inventory, mergeSource) { + if (mergeSource == null) emptyList() else model.inventory.filter { candidate -> + candidate.id != mergeSource.asset.id && + candidate.informationStatus != "INACTIVE" && + candidate.type?.id == mergeSource.asset.type?.id && + candidate.parent?.id == mergeSource.asset.parent?.id && + !candidate.captureRequired + } + } + + Column(Modifier.fillMaxSize()) { + Column(Modifier.padding(horizontal = 18.dp, vertical = 16.dp)) { + ModernHeader( + title = when (mode) { + ModernInventoryMode.PICK_PARENT -> "Elegir Instalación" + ModernInventoryMode.CREATE_INSTALLATION -> "Nueva Instalación" + ModernInventoryMode.CREATE_SUBINSTALLATION -> "Nueva Subinstalación" + ModernInventoryMode.BROWSE -> "Inventario de campo" + }, + subtitle = visit.scopeAsset?.name ?: visit.code, + onBack = { if (mode == ModernInventoryMode.BROWSE) onBack() else backToBrowse() }, + ) + if (model.busy) { + Spacer(Modifier.height(8.dp)) + LinearProgressIndicator(Modifier.fillMaxWidth()) + } + Spacer(Modifier.height(10.dp)) + ModernMessage(model) + localError?.let { ModernLocalError(it) { localError = null } } + } + + if (selectedCapture != null) { + ModernCaptureCard( + item = selectedCapture.asset, + gps = selectedCapture.capture.creationGpsCaptured, + photos = selectedCapture.capture.fieldPhotoCount, + ready = selectedCapture.capture.readyForFinding, + onPhoto = { requestPhoto() }, + onClose = { model.clearSelectedFieldAsset() }, + onCreateAnother = { + if (modernItemTypeCode(selectedCapture.asset) == "subinstalacion" && selectedCapture.asset.parent != null) { + chooseParent( + FieldInventoryItem( + id = selectedCapture.asset.parent.id, + code = selectedCapture.asset.parent.code, + name = selectedCapture.asset.parent.name, + type = null, + ), + ) + } else startSubinstallation() + }, + ) + } + + if (mergeSource != null && !mergeSource.capture.readyForFinding) { + ElevatedCard(Modifier.fillMaxWidth().padding(horizontal = 18.dp, vertical = 4.dp)) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text("¿Este elemento ya existía?", fontWeight = FontWeight.Bold) + Text("Podés fusionar el alta con un registro compatible sin perder historial.", style = MaterialTheme.typography.bodySmall) + OutlinedTextField( + value = mergeSearch, + onValueChange = { mergeSearch = it }, + label = { Text("Buscar posible duplicado") }, + leadingIcon = { Icon(Icons.Filled.Search, null) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + OutlinedButton( + onClick = { + mergeCandidateId = null + model.searchInventory(mergeSearch, mergeSource.asset.parent?.id) + }, + modifier = Modifier.fillMaxWidth(), + ) { Text("Buscar coincidencias") } + mergeCandidates.take(6).forEach { candidate -> + Surface( + onClick = { mergeCandidateId = candidate.id }, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + border = BorderStroke( + if (mergeCandidateId == candidate.id) 2.dp else 1.dp, + if (mergeCandidateId == candidate.id) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant, + ), + ) { + Text("${candidate.code} · ${candidate.name}", Modifier.padding(12.dp)) + } + } + AnimatedVisibility(mergeCandidateId != null) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = mergeReason, + onValueChange = { mergeReason = it }, + label = { Text("Motivo de la fusión") }, + modifier = Modifier.fillMaxWidth(), + minLines = 2, + ) + Button( + onClick = { model.mergeCreatedFieldAsset(mergeCandidateId!!, mergeReason) }, + enabled = mergeReason.trim().length >= 8 && !model.busy, + modifier = Modifier.fillMaxWidth(), + ) { Text("Fusionar con el existente") } + } + } + } + } + } + + when (mode) { + ModernInventoryMode.BROWSE -> ModernInventoryBrowse( + model = model, + search = search, + onSearchChange = { search = it }, + onStartSubinstallation = { startSubinstallation() }, + onStartInstallation = { startInstallation() }, + onChoose = { model.selectExisting(it) }, + onAddChild = { chooseParent(it) }, + ) + + ModernInventoryMode.PICK_PARENT -> { + val installations = model.inventory.filter { modernItemTypeCode(it) == "instalacion" } + Column(Modifier.fillMaxSize().padding(horizontal = 18.dp)) { + ModernStepHeader(1, "Elegí la Instalación padre") + Spacer(Modifier.height(6.dp)) + Text( + "Escribí nombre o código. Los resultados aparecen mientras buscás y podés tocarlos directamente.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(10.dp)) + OutlinedTextField( + value = parentSearch, + onValueChange = { parentSearch = it }, + label = { Text("Buscar Instalación") }, + placeholder = { Text("Ej. agua, batería, planta…") }, + leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) }, + trailingIcon = { + if (parentSearch.isNotBlank()) { + IconButton(onClick = { parentSearch = "" }) { + Icon(Icons.Filled.Close, contentDescription = "Limpiar búsqueda") + } + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { + keyboard?.hide() + focusManager.clearFocus() + }), + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + Spacer(Modifier.height(8.dp)) + Text( + if (installations.isEmpty() && !model.busy) "Sin coincidencias" else "${installations.size} Instalación${if (installations.size == 1) "" else "es"}", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(8.dp)) + if (installations.isEmpty() && !model.busy) { + ElevatedCard(Modifier.fillMaxWidth()) { + Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Icon(Icons.Filled.Search, null, tint = MaterialTheme.colorScheme.secondary) + Text("No encontramos una Instalación con ese texto.", fontWeight = FontWeight.SemiBold) + Text("Probá con parte del nombre o con el código.", style = MaterialTheme.typography.bodySmall) + OutlinedButton(onClick = { startInstallation() }) { Text("Crear nueva Instalación") } + } + } + } else { + LazyColumn( + Modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(9.dp), + ) { + items(installations, key = { it.id }) { item -> + ElevatedCard(onClick = { chooseParent(item) }, modifier = Modifier.fillMaxWidth()) { + Row( + Modifier.padding(15.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Surface(shape = MaterialTheme.shapes.small, color = MaterialTheme.colorScheme.primaryContainer) { + Icon(Icons.Filled.Factory, null, Modifier.padding(9.dp), tint = MaterialTheme.colorScheme.primary) + } + Column(Modifier.weight(1f)) { + Text(item.name, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(item.code, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + item.commonName?.takeIf { it.isNotBlank() }?.let { + Text(it, style = MaterialTheme.typography.bodySmall) + } + } + Icon(Icons.Filled.CheckCircle, contentDescription = "Seleccionar", tint = MaterialTheme.colorScheme.primary) + } + } + } + item { Spacer(Modifier.height(24.dp)) } + } + } + } + } + + ModernInventoryMode.CREATE_INSTALLATION, + ModernInventoryMode.CREATE_SUBINSTALLATION -> { + val isSubinstallation = mode == ModernInventoryMode.CREATE_SUBINSTALLATION + Column( + Modifier.fillMaxSize().padding(horizontal = 18.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(11.dp), + ) { + ModernStepHeader(if (isSubinstallation) 2 else 1, if (isSubinstallation) "Identificá la Subinstalación" else "Identificá la Instalación") + Surface( + Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + color = MaterialTheme.colorScheme.surfaceVariant, + ) { + Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.LocationOn, null, tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.width(8.dp)) + Text(parentLabel, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) + } + } + if (isSubinstallation) { + OutlinedButton(onClick = { startSubinstallation() }, modifier = Modifier.fillMaxWidth()) { + Text("Cambiar Instalación padre") + } + } + + if (model.fieldTypes.isEmpty() && !model.busy) { + ModernLocalError("No hay un tipo habilitado para esta ubicación.") {} + } + + if (model.fieldTypes.size > 1) { + Text("Nivel de Inventario", fontWeight = FontWeight.Bold) + model.fieldTypes.forEach { type -> + Surface( + onClick = { + selectedTypeId = type.id + selectedFamilyId = null + attributeValues.clear() + }, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + border = BorderStroke( + if (selectedTypeId == type.id) 2.dp else 1.dp, + if (selectedTypeId == type.id) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant, + ), + ) { Text(type.name, Modifier.padding(12.dp), fontWeight = if (selectedTypeId == type.id) FontWeight.Bold else FontWeight.Normal) } + } + } + + if (selectedType?.familyRequired == true) { + Text("Clasificación técnica", fontWeight = FontWeight.Bold) + OutlinedTextField( + value = familySearch, + onValueChange = { familySearch = it }, + label = { Text("Buscar clasificación") }, + leadingIcon = { Icon(Icons.Filled.Search, null) }, + supportingText = { Text("${filteredFamilies.size} opciones compatibles") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + filteredFamilies.take(12).forEach { family -> + Surface( + onClick = { selectedFamilyId = family.id }, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + color = if (selectedFamilyId == family.id) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, if (selectedFamilyId == family.id) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant), + ) { + Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + (if (family.isOther) "Otro · " else "") + family.name, + Modifier.weight(1f), + fontWeight = if (selectedFamilyId == family.id) FontWeight.Bold else FontWeight.Normal, + ) + if (selectedFamilyId == family.id) Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary) + } + } + } + if (filteredFamilies.size > 12) { + Text("Seguí escribiendo para reducir la lista.", style = MaterialTheme.typography.bodySmall) + } + selectedFamily?.let { family -> + if (family.isOther) { + Text("Quedará marcado para revisión en oficina.", color = MaterialTheme.colorScheme.secondary) + } + if (family.informationLabels.isNotEmpty()) { + Text("Datos esperados · ${family.informationLabels.joinToString(" · ")}", style = MaterialTheme.typography.bodySmall) + } + } + } + + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Nombre o código visible *") }, + supportingText = { Text("Usá lo que figura en placa o identifica el elemento en campo.") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + OutlinedTextField( + value = commonName, + onValueChange = { commonName = it }, + label = { Text("Nombre habitual") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + + selectedType?.attributes?.forEach { definition -> + OutlinedTextField( + value = attributeValues[definition.code].orEmpty(), + onValueChange = { attributeValues[definition.code] = it }, + label = { Text(definition.name + if (definition.isRequired) " *" else "") }, + supportingText = { + val details = listOfNotNull(definition.unit, definition.options?.toString()).joinToString(" · ") + if (details.isNotBlank()) Text(details) + }, + keyboardOptions = KeyboardOptions( + keyboardType = if (definition.dataType.uppercase() in setOf("NUMBER", "DECIMAL", "INTEGER", "FLOAT")) KeyboardType.Decimal else KeyboardType.Text, + ), + modifier = Modifier.fillMaxWidth(), + ) + } + + HorizontalDivider() + ModernStepHeader(if (isSubinstallation) 3 else 2, "GPS + foto") + Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.secondaryContainer) { + Row(Modifier.padding(14.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.CameraAlt, null, tint = MaterialTheme.colorScheme.secondary) + Text( + "Al guardar capturamos el GPS y abrimos la cámara. La foto es obligatoria antes de registrar Hallazgos.", + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f), + ) + } + } + + val attributesReady = selectedType?.attributes + ?.filter { it.isRequired } + ?.all { attributeValues[it.code].orEmpty().isNotBlank() } + ?: false + val familyReady = selectedType?.familyRequired != true || selectedFamilyId != null + Button( + onClick = { requestCreate() }, + enabled = selectedType != null && name.isNotBlank() && attributesReady && familyReady && !model.busy, + modifier = Modifier.fillMaxWidth(), + ) { + Icon(Icons.Filled.CameraAlt, null) + Spacer(Modifier.width(8.dp)) + Text(if (model.busy) "Guardando…" else "Guardar y tomar foto") + } + Spacer(Modifier.height(32.dp)) + } + } + } + } +} + +@Composable +private fun ModernInventoryBrowse( + model: MainViewModel, + search: String, + onSearchChange: (String) -> Unit, + onStartSubinstallation: () -> Unit, + onStartInstallation: () -> Unit, + onChoose: (FieldInventoryItem) -> Unit, + onAddChild: (FieldInventoryItem) -> Unit, +) { + val focusManager = LocalFocusManager.current + val keyboard = LocalSoftwareKeyboardController.current + val rows = model.inventory.filter { modernItemTypeCode(it) in setOf("instalacion", "subinstalacion") } + Column(Modifier.fillMaxSize().padding(horizontal = 18.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(onClick = onStartSubinstallation, modifier = Modifier.weight(1f)) { + Icon(Icons.Filled.Add, null) + Spacer(Modifier.width(5.dp)) + Text("Subinstalación") + } + FilledTonalButton(onClick = onStartInstallation, modifier = Modifier.weight(1f)) { + Icon(Icons.Filled.Add, null) + Spacer(Modifier.width(5.dp)) + Text("Instalación") + } + } + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = search, + onValueChange = onSearchChange, + label = { Text("Buscar Inventario") }, + placeholder = { Text("Nombre, código o dato técnico") }, + leadingIcon = { Icon(Icons.Filled.Search, null) }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { keyboard?.hide(); focusManager.clearFocus() }), + modifier = Modifier.fillMaxWidth(), + singleLine = true, + ) + Spacer(Modifier.height(10.dp)) + Text("${rows.size} resultados", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(8.dp)) + LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(9.dp)) { + items(rows, key = { it.id }) { item -> + ModernInventoryCard(item = item, onInspect = { onChoose(item) }, onAddChild = { onAddChild(item) }) + } + item { Spacer(Modifier.height(28.dp)) } + } + } +} + +@Composable +private fun ModernInventoryCard(item: FieldInventoryItem, onInspect: () -> Unit, onAddChild: () -> Unit) { + val typeCode = modernItemTypeCode(item) + ElevatedCard(Modifier.fillMaxWidth()) { + Column(Modifier.padding(15.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Top) { + Column(Modifier.weight(1f)) { + Text(item.name, fontWeight = FontWeight.Bold) + Text(item.code, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + StatusPill(if (typeCode == "subinstalacion") "Subinstalación" else "Instalación") + } + item.commonName?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodySmall) } + Text( + if (item.readyForFinding) "Listo para Hallazgos" else "Falta GPS / foto", + color = if (item.readyForFinding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.SemiBold, + ) + Button(onClick = onInspect, modifier = Modifier.fillMaxWidth()) { + Text(if (item.selectedInInspection) "Abrir para Hallazgo" else "Seleccionar para Hallazgo") + } + if (typeCode == "instalacion") { + OutlinedButton(onClick = onAddChild, modifier = Modifier.fillMaxWidth()) { + Icon(Icons.Filled.Add, null) + Spacer(Modifier.width(6.dp)) + Text("Agregar Subinstalación") + } + } + } + } +} + +@Composable +private fun ModernCaptureCard( + item: FieldInventoryItem, + gps: Boolean, + photos: Int, + ready: Boolean, + onPhoto: () -> Unit, + onClose: () -> Unit, + onCreateAnother: () -> Unit, +) { + ElevatedCard(Modifier.fillMaxWidth().padding(horizontal = 18.dp, vertical = 4.dp)) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Top) { + Column(Modifier.weight(1f)) { + Text(item.name, fontWeight = FontWeight.Bold) + Text(item.code, style = MaterialTheme.typography.bodySmall) + } + IconButton(onClick = onClose) { Icon(Icons.Filled.Close, "Cerrar") } + } + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(if (gps) "✓ GPS" else "GPS pendiente", color = if (gps) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error) + Text("Fotos · $photos") + } + if (!ready) { + Text("Completá la fotografía para habilitar Hallazgos.", color = MaterialTheme.colorScheme.error) + Button(onClick = onPhoto, modifier = Modifier.fillMaxWidth()) { + Icon(Icons.Filled.CameraAlt, null) + Spacer(Modifier.width(6.dp)) + Text("Tomar foto ahora") + } + } else { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.width(7.dp)) + Text("Alta completa", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold) + } + OutlinedButton(onClick = onCreateAnother, modifier = Modifier.fillMaxWidth()) { + Text("Crear otra Subinstalación") + } + } + } + } +} + +@Composable +internal fun ModernHeader(title: String, subtitle: String? = null, onBack: () -> Unit) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = MaterialTheme.shapes.medium, tonalElevation = 1.dp) { + IconButton(onClick = onBack) { Icon(Icons.Filled.ArrowBack, contentDescription = "Atrás") } + } + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + subtitle?.takeIf { it.isNotBlank() }?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } +} + +@Composable +internal fun StatusPill(text: String) { + Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceVariant) { + Text(text, Modifier.padding(horizontal = 10.dp, vertical = 5.dp), style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.SemiBold) + } +} + +@Composable +internal fun ModernMessage(model: MainViewModel) { + val error = model.error + val notice = model.notice + if (error != null || notice != null) { + Surface( + onClick = { model.clearMessages() }, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + color = if (error != null) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.secondaryContainer, + ) { + Row(Modifier.padding(13.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon( + if (error != null) Icons.Filled.WarningAmber else Icons.Filled.CheckCircle, + contentDescription = null, + tint = if (error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.secondary, + ) + Text(error ?: notice.orEmpty(), Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) + Icon(Icons.Filled.Close, contentDescription = "Cerrar mensaje") + } + } + } +} + +@Composable +private fun ModernLocalError(message: String, onDismiss: () -> Unit) { + Surface( + onClick = onDismiss, + modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), + shape = MaterialTheme.shapes.medium, + color = MaterialTheme.colorScheme.errorContainer, + ) { + Row(Modifier.padding(13.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(9.dp)) { + Icon(Icons.Filled.WarningAmber, null, tint = MaterialTheme.colorScheme.error) + Text(message, Modifier.weight(1f), color = MaterialTheme.colorScheme.onErrorContainer) + Icon(Icons.Filled.Close, "Cerrar") + } + } +} + +@Composable +private fun ModernStepHeader(step: Int, title: String) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.primaryContainer) { + Text(step.toString(), Modifier.padding(horizontal = 11.dp, vertical = 7.dp), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary) + } + Spacer(Modifier.width(9.dp)) + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + } +} + +private fun modernItemTypeCode(item: FieldInventoryItem): String { + val type = item.type ?: return "" + return modernNormalize(type.typeName ?: type.name) +} + +private fun modernNormalize(value: String): String = value.trim().lowercase() + .replace('ó', 'o').replace('í', 'i').replace('á', 'a').replace('é', 'e').replace('ú', 'u') + .replace("_", "").replace("-", "").replace(" ", "") + +private fun modernStatusLabel(status: String): String = when (status) { + "PLANNED" -> "Planificada" + "IN_PROGRESS" -> "En curso" + "CLOSED" -> "Cerrada" + "CANCELLED" -> "Cancelada" + else -> status +} + +private fun buildModernAttributes(type: FieldType, values: Map): Map = + type.attributes.mapNotNull { definition -> + val raw = values[definition.code]?.trim().orEmpty() + if (raw.isBlank()) return@mapNotNull null + definition.code to coerceModernAttribute(definition, raw) + }.toMap() + +private fun coerceModernAttribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) { + "INTEGER", "INT" -> raw.toLongOrNull() ?: raw + "NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw + "BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes") + else -> raw +} + +private fun modernHasPermission(context: Context, permission: String): Boolean = + ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED + +private fun modernHasLocation(context: Context): Boolean = + modernHasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) || modernHasPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) + +private suspend fun currentModernGeo(context: Context): ModernGeoSnapshot = suspendCancellableCoroutine { continuation -> + if (!modernHasLocation(context)) { + continuation.resumeWithException(SecurityException("Se necesita permiso de ubicación.")) + return@suspendCancellableCoroutine + } + val source = CancellationTokenSource() + val client = LocationServices.getFusedLocationProviderClient(context) + try { + client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, source.token) + .addOnSuccessListener { location -> + if (!continuation.isActive) return@addOnSuccessListener + if (location == null) continuation.resumeWithException(IllegalStateException("No se pudo obtener una ubicación GPS actual.")) + else continuation.resume(ModernGeoSnapshot(location.latitude, location.longitude, location.accuracy.toDouble())) + } + .addOnFailureListener { if (continuation.isActive) continuation.resumeWithException(it) } + } catch (error: SecurityException) { + if (continuation.isActive) continuation.resumeWithException(error) + } + continuation.invokeOnCancellation { source.cancel() } +} + +private fun newModernPhoto(context: Context): Pair { + val directory = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + ?: throw IllegalStateException("No se pudo acceder al almacenamiento de fotografías.") + directory.mkdirs() + val file = File.createTempFile("DH_FAST_${System.currentTimeMillis()}_", ".jpg", directory) + val uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file) + return file to uri +} + +private fun writeModernExif(file: File, geo: ModernGeoSnapshot) { + val now = Instant.now() + val exif = ExifInterface(file) + exif.setLatLong(geo.latitude, geo.longitude) + val formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss").withZone(ZoneId.systemDefault()) + exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, formatter.format(now)) + exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, formatter.format(now)) + exif.saveAttributes() +} + +private fun modernShortDate(value: String): String = value.replace('T', ' ').take(16)