diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 261ac53..8e2e10c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -6,7 +6,6 @@ - + when (event) { + is UiEvent.ShowSnackbar -> snackbarHostState.showSnackbar(event.message) + is UiEvent.OpenUrl -> { + try { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(event.url)) + context.startActivity(intent) + } catch (_: Exception) { + snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : ${event.url}") + } + } + is UiEvent.StartActivity -> context.startActivity(event.intent) + } + } + } + var currentTab by remember { mutableStateOf(MainTab.JOURNAL) } var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) } var editingMeal by remember { mutableStateOf(null) } @@ -201,6 +220,7 @@ fun AppRoot( } val mealsState by viewModel.mealsState.collectAsStateWithLifecycle() + val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle() val customFoods by viewModel.customFoods.collectAsStateWithLifecycle() val themeMode by viewModel.themeMode.collectAsStateWithLifecycle() val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle() @@ -450,9 +470,6 @@ fun AppRoot( } MainTab.STATS -> { - val weeklyStats = remember(currentMealsList) { - viewModel.computeWeeklyStats(currentMealsList) - } WeeklyStatsScreen( weeklyStats = weeklyStats, totalMealsCount = currentMealsList.size, @@ -489,10 +506,11 @@ fun AppRoot( onOpenSheetsClick = { url -> openGoogleSheets(url) }, onSignInClick = { showAuthSheet = true }, onSignOut = { - currentUser = null - viewModel.disconnectGoogleSheets() - coroutineScope.launch { - snackbarHostState.showSnackbar("Mode local actif • Déconnecté") + viewModel.signOut(context) { + currentUser = null + coroutineScope.launch { + snackbarHostState.showSnackbar("Mode local actif • Déconnecté") + } } } ) @@ -522,7 +540,7 @@ fun AppRoot( hungerBefore = hunger, satietyAfter = satiety, note = note, - photosBase64 = photos + photoUris = photos ), foodItems = foodItems, onSuccess = { @@ -544,7 +562,7 @@ fun AppRoot( satietyAfter = satiety, note = note, foodItems = foodItems, - photosBase64 = photos, + photoUris = photos, onSuccess = { coroutineScope.launch { snackbarHostState.showSnackbar("Repas enregistré avec succès ✨") diff --git a/app/src/main/java/com/example/data/local/AppDatabase.kt b/app/src/main/java/com/example/data/local/AppDatabase.kt index 51a8b18..c373099 100644 --- a/app/src/main/java/com/example/data/local/AppDatabase.kt +++ b/app/src/main/java/com/example/data/local/AppDatabase.kt @@ -7,7 +7,7 @@ import androidx.room.RoomDatabase @Database( entities = [LocalMealEntity::class, LocalCustomFoodEntity::class], - version = 1, + version = 2, exportSchema = false ) abstract class AppDatabase : RoomDatabase() { @@ -24,7 +24,7 @@ abstract class AppDatabase : RoomDatabase() { context.applicationContext, AppDatabase::class.java, "satiea_local.db" - ).fallbackToDestructiveMigration().build().also { INSTANCE = it } + ).fallbackToDestructiveMigration(true).build().also { INSTANCE = it } } } } diff --git a/app/src/main/java/com/example/data/local/LocalMealEntity.kt b/app/src/main/java/com/example/data/local/LocalMealEntity.kt index e39e1f5..0222b39 100644 --- a/app/src/main/java/com/example/data/local/LocalMealEntity.kt +++ b/app/src/main/java/com/example/data/local/LocalMealEntity.kt @@ -3,7 +3,6 @@ package com.example.data.local import androidx.room.Entity import androidx.room.PrimaryKey import com.example.data.model.MealEntry -import com.example.data.model.MealFoodItem @Entity(tableName = "local_meals") data class LocalMealEntity( @@ -14,8 +13,8 @@ data class LocalMealEntity( val hungerBefore: Int, val satietyAfter: Int, val note: String = "", - val foodItemsJoined: String = "", // serialized items separated by "###" - val photosJoined: String = "", // Base64 photos separated by "|||" + val foodItemsJoined: String = "", // serialized items separated by "###" + val photoUrisJoined: String = "", // local file URIs separated by "|||" val updatedAt: Long = System.currentTimeMillis() ) { fun toMealEntry(): MealEntry { @@ -24,10 +23,10 @@ data class LocalMealEntity( } else { foodItemsJoined.split("###").filter { it.isNotBlank() } } - val photos = if (photosJoined.isBlank()) { + val photos = if (photoUrisJoined.isBlank()) { emptyList() } else { - photosJoined.split("|||").filter { it.isNotBlank() } + photoUrisJoined.split("|||").filter { it.isNotBlank() } } return MealEntry( id = id, @@ -38,14 +37,15 @@ data class LocalMealEntity( satietyAfter = satietyAfter, note = note, foodItemsSerialized = foodItems, - photosBase64 = photos + photoUris = photos, + photosBase64 = emptyList() ) } companion object { fun fromMealEntry(meal: MealEntry): LocalMealEntity { val foodItemsJoined = meal.foodItemsSerialized.joinToString("###") - val photosJoined = meal.photosBase64.joinToString("|||") + val photoUrisJoined = meal.displayPhotoUris.joinToString("|||") return LocalMealEntity( id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" }, userId = meal.userId, @@ -55,7 +55,7 @@ data class LocalMealEntity( satietyAfter = meal.satietyAfter, note = meal.note, foodItemsJoined = foodItemsJoined, - photosJoined = photosJoined, + photoUrisJoined = photoUrisJoined, updatedAt = System.currentTimeMillis() ) } diff --git a/app/src/main/java/com/example/data/model/MealEntry.kt b/app/src/main/java/com/example/data/model/MealEntry.kt index 183da2b..9212d5d 100644 --- a/app/src/main/java/com/example/data/model/MealEntry.kt +++ b/app/src/main/java/com/example/data/model/MealEntry.kt @@ -92,10 +92,14 @@ data class MealEntry( val satietyAfter: Int = 7, val note: String = "", val foodItemsSerialized: List = emptyList(), + val photoUris: List = emptyList(), val photosBase64: List = emptyList(), @ServerTimestamp val createdAt: Timestamp? = null, @ServerTimestamp val updatedAt: Timestamp? = null ) { + val displayPhotoUris: List + get() = photoUris.ifEmpty { photosBase64 } + fun parsedFoodItems(): List { return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) } } @@ -109,7 +113,7 @@ data class MealEntry( "satietyAfter" to satietyAfter.coerceIn(1, 10), "note" to note, "foodItemsSerialized" to foodItemsSerialized.take(30), - "photosBase64" to photosBase64, + "photoUris" to photoUris.take(6), "createdAt" to createdAt, "updatedAt" to updatedAt ) diff --git a/app/src/main/java/com/example/data/repository/FirestoreErrorHandler.kt b/app/src/main/java/com/example/data/repository/FirestoreErrorHandler.kt index 804ff61..ac8c14c 100644 --- a/app/src/main/java/com/example/data/repository/FirestoreErrorHandler.kt +++ b/app/src/main/java/com/example/data/repository/FirestoreErrorHandler.kt @@ -28,13 +28,11 @@ fun handleFirestoreError(exception: Throwable, operationType: OperationType, pat val providerInfoList = currentUser?.providerData?.map { provider -> JSONObject().apply { put("providerId", provider.providerId) - put("email", provider.email) } } ?: emptyList() val authInfoJson = JSONObject().apply { put("userId", currentUser?.uid) - put("email", currentUser?.email) put("emailVerified", currentUser?.isEmailVerified) put("tenantId", currentUser?.tenantId) put("providerInfo", JSONArray(providerInfoList)) diff --git a/app/src/main/java/com/example/data/repository/MealRepository.kt b/app/src/main/java/com/example/data/repository/MealRepository.kt index 6b709e1..a3b63f6 100644 --- a/app/src/main/java/com/example/data/repository/MealRepository.kt +++ b/app/src/main/java/com/example/data/repository/MealRepository.kt @@ -13,7 +13,9 @@ import com.example.data.model.FoodUnit import com.example.data.model.MealEntry import com.example.util.CsvImportResult import com.example.util.CsvImporter +import com.example.util.ImageUtils import com.google.firebase.Firebase +import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore @@ -32,7 +34,8 @@ import java.util.UUID class MealRepository( private val localMealDao: LocalMealDao?, - private val db: FirebaseFirestore? + private val db: FirebaseFirestore?, + private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth ) { // Constructor used by ViewModel in app runtime @@ -50,11 +53,10 @@ class MealRepository( // Secondary constructor for Firestore rule tests without local DB constructor(db: FirebaseFirestore) : this( localMealDao = null, - db = db + db = db, + auth = FirebaseAuth.getInstance(db.app) ) - private val auth = Firebase.auth - private fun getUserIdOrNull(): String? { return auth.currentUser?.uid } @@ -152,6 +154,7 @@ class MealRepository( ) docRef.set(payload).await() } catch (e: Exception) { + if (e is CancellationException) throw e if (localMealDao == null) { handleFirestoreError(e, OperationType.CREATE, docRef.path) return Result.failure(e) @@ -209,6 +212,7 @@ class MealRepository( val docRef = mealsRef.document(resolvedId) docRef.set(payload).await() } catch (e: Exception) { + if (e is CancellationException) throw e if (localMealDao == null) { handleFirestoreError(e, OperationType.CREATE, path) return Result.failure(e) @@ -238,11 +242,12 @@ class MealRepository( "satietyAfter" to meal.satietyAfter.coerceIn(1, 10), "note" to meal.note, "foodItemsSerialized" to meal.foodItemsSerialized.take(30), - "photosBase64" to meal.photosBase64, + "photoUris" to meal.photoUris.take(6), "updatedAt" to FieldValue.serverTimestamp() ) docRef.update(updates).await() } catch (e: Exception) { + if (e is CancellationException) throw e if (localMealDao == null) { handleFirestoreError(e, OperationType.UPDATE, docRef.path) return Result.failure(e) @@ -255,16 +260,23 @@ class MealRepository( } suspend fun deleteMeal(mealId: String): Result { - // 1. Delete from local Room database + // 1. Clean up local photo files + val existingMeal = localMealDao?.getMealById(mealId)?.toMealEntry() + existingMeal?.displayPhotoUris?.forEach { uri -> + ImageUtils.deletePhotoFile(uri) + } + + // 2. Delete from local Room database localMealDao?.deleteMealById(mealId) - // 2. If signed in, delete from Firestore + // 3. If signed in, delete from Firestore val uid = getUserIdOrNull() if (uid != null && db != null) { val docRef = db.collection("users").document(uid).collection("meals").document(mealId) try { docRef.delete().await() } catch (e: Exception) { + if (e is CancellationException) throw e if (localMealDao == null) { handleFirestoreError(e, OperationType.DELETE, docRef.path) return Result.failure(e) @@ -341,6 +353,7 @@ class MealRepository( Result.success(result) } catch (e: Exception) { + if (e is CancellationException) throw e Result.failure(e) } } @@ -389,6 +402,7 @@ class MealRepository( Result.success(importedCount) } catch (e: Exception) { + if (e is CancellationException) throw e Result.failure(e) } } diff --git a/app/src/main/java/com/example/domain/CsvExportUseCase.kt b/app/src/main/java/com/example/domain/CsvExportUseCase.kt new file mode 100644 index 0000000..20f7cc2 --- /dev/null +++ b/app/src/main/java/com/example/domain/CsvExportUseCase.kt @@ -0,0 +1,22 @@ +package com.example.domain + +import android.content.Context +import android.content.Intent +import android.net.Uri +import com.example.data.model.MealEntry +import com.example.util.CsvExporter + +class CsvExportUseCase(private val context: Context) { + + suspend fun writeToUri(targetUri: Uri, meals: List): Result { + return CsvExporter.writeCsvToUri(context, targetUri, meals) + } + + suspend fun createShareIntent(activityContext: Context, meals: List): Result { + return CsvExporter.shareCsvFile(activityContext, meals) + } + + fun defaultFileName(): String { + return CsvExporter.buildDefaultFileName() + } +} diff --git a/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt new file mode 100644 index 0000000..a98ecba --- /dev/null +++ b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt @@ -0,0 +1,87 @@ +package com.example.domain + +import android.content.Context +import android.content.Intent +import com.example.data.model.MealEntry +import com.example.data.preferences.GoogleSheetsPreferencesManager +import com.example.data.repository.MealRepository +import com.example.util.GoogleSheetsAuthHelper +import com.example.util.GoogleSheetsSyncResult +import com.example.util.GoogleSheetsSyncService +import com.google.android.gms.auth.UserRecoverableAuthException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +sealed interface SheetsSyncResult { + data class Success(val url: String, val count: Int, val timestamp: Long) : SheetsSyncResult + data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsSyncResult + data class Failure(val message: String) : SheetsSyncResult +} + +class GoogleSheetsSyncUseCase( + private val context: Context, + private val repository: MealRepository, + private val sheetsPrefs: GoogleSheetsPreferencesManager +) { + + suspend fun execute(): SheetsSyncResult = withContext(Dispatchers.IO) { + val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context) + if (tokenResult.isFailure) { + val exception = tokenResult.exceptionOrNull() + return@withContext if (exception is UserRecoverableAuthException) { + SheetsSyncResult.RecoverableAuth( + message = "Autorisation requise pour Google Sheets & Drive", + intent = exception.intent + ) + } else { + SheetsSyncResult.Failure(exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google") + } + } + + val token = tokenResult.getOrThrow() + val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) + if (spreadsheetResult.isFailure) { + val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création du classeur" + return@withContext SheetsSyncResult.Failure(err) + } + + val (id, url) = spreadsheetResult.getOrThrow() + sheetsPrefs.spreadsheetId = id + sheetsPrefs.spreadsheetUrl = url + + val currentMeals = repository.getAllMealsSnapshot() + val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) + if (syncResult.isSuccess) { + val res = syncResult.getOrThrow() + sheetsPrefs.lastSyncTimestamp = res.timestamp + sheetsPrefs.lastSyncCount = res.mealsCount + sheetsPrefs.lastSyncStatus = "Synchronisé avec succès" + SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp) + } else { + val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas" + SheetsSyncResult.Failure(err) + } + } + + suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? = withContext(Dispatchers.IO) { + if (!sheetsPrefs.isAutoSyncEnabled) return@withContext null + try { + val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null + val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId).getOrNull() ?: return@withContext null + sheetsPrefs.spreadsheetId = id + sheetsPrefs.spreadsheetUrl = url + + val currentMeals = repository.getAllMealsSnapshot() + val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) + if (syncResult.isSuccess) { + val res = syncResult.getOrThrow() + sheetsPrefs.lastSyncTimestamp = res.timestamp + sheetsPrefs.lastSyncCount = res.mealsCount + sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement" + res + } else null + } catch (_: Exception) { + null + } + } +} diff --git a/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt b/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt new file mode 100644 index 0000000..b977911 --- /dev/null +++ b/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt @@ -0,0 +1,81 @@ +package com.example.domain + +import com.example.data.model.MealEntry +import com.example.data.model.MealType +import com.example.ui.journal.DayStat +import com.example.ui.journal.WeeklyStats +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale + +object WeeklyStatsCalculator { + + fun computeWeeklyStats(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { + val todayLocalDate = LocalDate.now(zoneId) + val startOfPeriod = todayLocalDate.minusDays(6) + val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli() + val endOfTodayMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 + + val recentMeals = meals.filter { it.mealTimestamp in startOfPeriodMillis..endOfTodayMillis } + + val dayFormat = DateTimeFormatter.ofPattern("EEE", Locale.FRENCH) + val fullDayFormat = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) + + val daysList = mutableListOf() + + for (i in 6 downTo 0) { + val currentDay = todayLocalDate.minusDays(i.toLong()) + val startOfDay = currentDay.atStartOfDay(zoneId).toInstant().toEpochMilli() + val endOfDay = currentDay.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 + + val dayMeals = meals.filter { it.mealTimestamp in startOfDay..endOfDay } + + val avgSatiety = if (dayMeals.isNotEmpty()) { + dayMeals.map { it.satietyAfter }.average().toFloat() + } else 0f + + val avgHunger = if (dayMeals.isNotEmpty()) { + dayMeals.map { it.hungerBefore }.average().toFloat() + } else 0f + + daysList.add( + DayStat( + dayLabel = fullDayFormat.format(currentDay), + dayShortName = dayFormat.format(currentDay).replace(".", "").replaceFirstChar { + if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() + }, + timestampMillis = startOfDay, + avgSatiety = avgSatiety, + avgHunger = avgHunger, + mealCount = dayMeals.size + ) + ) + } + + val allRecentSatieties = recentMeals.map { it.satietyAfter } + val allRecentHungers = recentMeals.map { it.hungerBefore } + + val avgSatiety = if (allRecentSatieties.isNotEmpty()) allRecentSatieties.average().toFloat() else 0f + val avgHunger = if (allRecentHungers.isNotEmpty()) allRecentHungers.average().toFloat() else 0f + + val optimalCount = recentMeals.count { it.satietyAfter in 6..8 } + val optimalPercentage = if (recentMeals.isNotEmpty()) { + ((optimalCount.toFloat() / recentMeals.size) * 100).toInt() + } else 0 + + val distribution = mutableMapOf() + MealType.entries.forEach { type -> + distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) } + } + + return WeeklyStats( + dailyStats = daysList, + averageSatiety = avgSatiety, + averageHunger = avgHunger, + optimalZonePercentage = optimalPercentage, + totalMealsLast7Days = recentMeals.size, + mealTypeDistribution = distribution + ) + } +} diff --git a/app/src/main/java/com/example/notification/MealNotificationManager.kt b/app/src/main/java/com/example/notification/MealNotificationManager.kt index f6b9444..b578b0c 100644 --- a/app/src/main/java/com/example/notification/MealNotificationManager.kt +++ b/app/src/main/java/com/example/notification/MealNotificationManager.kt @@ -15,7 +15,8 @@ import com.example.R import com.example.data.model.MealType import com.example.data.preferences.ReminderPreferencesManager import com.example.receiver.MealReminderReceiver -import java.util.Calendar +import java.time.ZoneId +import java.time.ZonedDateTime object MealNotificationManager { @@ -111,55 +112,31 @@ object MealNotificationManager { return } - val calendar = Calendar.getInstance().apply { - timeInMillis = System.currentTimeMillis() - set(Calendar.HOUR_OF_DAY, hour) - set(Calendar.MINUTE, minute) - set(Calendar.SECOND, 0) - set(Calendar.MILLISECOND, 0) - if (timeInMillis <= System.currentTimeMillis()) { - add(Calendar.DAY_OF_YEAR, 1) - } + val zoneId = ZoneId.systemDefault() + val nowZoned = ZonedDateTime.now(zoneId) + var triggerZoned = nowZoned.withHour(hour).withMinute(minute).withSecond(0).withNano(0) + if (!triggerZoned.isAfter(nowZoned)) { + triggerZoned = triggerZoned.plusDays(1) } + val triggerMillis = triggerZoned.toInstant().toEpochMilli() try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - if (alarmManager.canScheduleExactAlarms()) { - alarmManager.setExactAndAllowWhileIdle( - AlarmManager.RTC_WAKEUP, - calendar.timeInMillis, - pendingIntent - ) - } else { - alarmManager.setAndAllowWhileIdle( - AlarmManager.RTC_WAKEUP, - calendar.timeInMillis, - pendingIntent - ) - } - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - alarmManager.setExactAndAllowWhileIdle( - AlarmManager.RTC_WAKEUP, - calendar.timeInMillis, - pendingIntent - ) - } else { - alarmManager.setExact( - AlarmManager.RTC_WAKEUP, - calendar.timeInMillis, - pendingIntent - ) - } - Log.d(TAG, "Scheduled exact reminder for ${mealType.name} at ${calendar.time}") - } catch (e: SecurityException) { - Log.w(TAG, "Exact alarm permission not granted, falling back to setAndAllowWhileIdle", e) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { alarmManager.setAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, - calendar.timeInMillis, + triggerMillis, + pendingIntent + ) + } else { + alarmManager.set( + AlarmManager.RTC_WAKEUP, + triggerMillis, pendingIntent ) } + Log.d(TAG, "Scheduled reminder for ${mealType.name} at $triggerZoned") + } catch (e: Exception) { + Log.w(TAG, "Could not schedule reminder: ${e.message}") } } diff --git a/app/src/main/java/com/example/ui/common/UiEvent.kt b/app/src/main/java/com/example/ui/common/UiEvent.kt new file mode 100644 index 0000000..bd13433 --- /dev/null +++ b/app/src/main/java/com/example/ui/common/UiEvent.kt @@ -0,0 +1,9 @@ +package com.example.ui.common + +import android.content.Intent + +sealed interface UiEvent { + data class ShowSnackbar(val message: String) : UiEvent + data class OpenUrl(val url: String) : UiEvent + data class StartActivity(val intent: Intent) : UiEvent +} diff --git a/app/src/main/java/com/example/ui/journal/JournalScreen.kt b/app/src/main/java/com/example/ui/journal/JournalScreen.kt index 52b6870..7875a97 100644 --- a/app/src/main/java/com/example/ui/journal/JournalScreen.kt +++ b/app/src/main/java/com/example/ui/journal/JournalScreen.kt @@ -2,6 +2,7 @@ package com.example.ui.journal import android.graphics.Bitmap import androidx.compose.foundation.Image +import coil.compose.AsyncImage import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -64,9 +65,10 @@ import com.example.data.model.HungerSatietyScale import com.example.data.model.MealEntry import com.example.data.model.MealType import com.example.util.ImageUtils -import java.text.SimpleDateFormat -import java.util.Calendar -import java.util.Date +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale @Composable @@ -115,14 +117,10 @@ fun JournalScreen( is MealsUiState.Success -> { val meals = mealsUiState.meals - val todayCalendar = Calendar.getInstance().apply { - set(Calendar.HOUR_OF_DAY, 0) - set(Calendar.MINUTE, 0) - set(Calendar.SECOND, 0) - set(Calendar.MILLISECOND, 0) - } - val todayStartMillis = todayCalendar.timeInMillis - val todayEndMillis = todayStartMillis + (24L * 60 * 60 * 1000) - 1 + val zoneId = ZoneId.systemDefault() + val todayLocalDate = LocalDate.now(zoneId) + val todayStartMillis = todayLocalDate.atStartOfDay(zoneId).toInstant().toEpochMilli() + val todayEndMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis } LazyColumn( @@ -236,9 +234,9 @@ fun JournalScreen( @Composable private fun DailyOverviewCard(todayMeals: List) { - val dateFormat = remember { SimpleDateFormat("EEEE d MMMM", Locale.FRENCH) } + val dateFormatter = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) } val todayFormatted = remember { - dateFormat.format(Date()).replaceFirstChar { + dateFormatter.format(LocalDate.now()).replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() } } @@ -338,7 +336,8 @@ private fun MealCardItem( ) { var showMenu by remember { mutableStateOf(false) } var showDeleteDialog by remember { mutableStateOf(false) } - val dateTimeFormat = remember { SimpleDateFormat("EEE d MMM yyyy • HH:mm", Locale.FRENCH) } + val dateTimeFormatter = remember { DateTimeFormatter.ofPattern("EEE d MMM yyyy • HH:mm", Locale.FRENCH) } + val zoneId = remember { ZoneId.systemDefault() } val mealType = MealType.fromString(meal.mealType) val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() } @@ -397,7 +396,7 @@ private fun MealCardItem( ) Spacer(modifier = Modifier.width(4.dp)) Text( - text = dateTimeFormat.format(Date(meal.mealTimestamp)).replaceFirstChar { + text = dateTimeFormatter.format(Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)).replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() }, style = MaterialTheme.typography.bodySmall, @@ -544,23 +543,20 @@ private fun MealCardItem( } // Photos Carousel - if (meal.photosBase64.isNotEmpty()) { + if (meal.displayPhotoUris.isNotEmpty()) { Spacer(modifier = Modifier.height(14.dp)) LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - items(meal.photosBase64) { b64 -> - val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) } - if (bitmap != null) { - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = "Photo assiette", - modifier = Modifier - .size(76.dp) - .clip(RoundedCornerShape(12.dp)), - contentScale = ContentScale.Crop - ) - } + items(meal.displayPhotoUris) { photoUri -> + AsyncImage( + model = photoUri, + contentDescription = "Photo du repas", + modifier = Modifier + .size(76.dp) + .clip(RoundedCornerShape(12.dp)), + contentScale = ContentScale.Crop + ) } } } diff --git a/app/src/main/java/com/example/ui/journal/MealViewModel.kt b/app/src/main/java/com/example/ui/journal/MealViewModel.kt index ab50278..49f9f3f 100644 --- a/app/src/main/java/com/example/ui/journal/MealViewModel.kt +++ b/app/src/main/java/com/example/ui/journal/MealViewModel.kt @@ -11,26 +11,33 @@ import com.example.data.model.DefaultFoodCatalog import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType -import com.example.data.repository.MealRepository import com.example.data.preferences.GoogleSheetsPreferencesManager +import com.example.data.repository.MealRepository +import com.example.domain.CsvExportUseCase +import com.example.domain.GoogleSheetsSyncUseCase +import com.example.domain.SheetsSyncResult import com.example.notification.MealNotificationManager +import com.example.ui.common.UiEvent import com.example.ui.theme.AppThemeMode -import com.example.util.CsvExporter -import com.example.util.GoogleSheetsAuthHelper -import com.example.util.GoogleSheetsSyncService -import com.google.android.gms.auth.UserRecoverableAuthException +import com.example.util.CsvImportResult +import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestoreException import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch -import java.text.SimpleDateFormat -import java.util.Calendar +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale sealed interface MealsUiState { @@ -62,12 +69,36 @@ data class WeeklyStats( val optimalZonePercentage: Int, val totalMealsLast7Days: Int, val mealTypeDistribution: Map -) +) { + companion object { + fun empty(): WeeklyStats = WeeklyStats( + dailyStats = emptyList(), + averageSatiety = 0f, + averageHunger = 0f, + optimalZonePercentage = 0, + totalMealsLast7Days = 0, + mealTypeDistribution = emptyMap() + ) + } +} class MealViewModel(application: Application) : AndroidViewModel(application) { private val repository = MealRepository(application) private val context = application.applicationContext + private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application) + + // Domain Use Cases + private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs) + private val csvExportUseCase = CsvExportUseCase(context) + + // UDF Event Channel + private val _uiEventChannel = Channel(Channel.BUFFERED) + val uiEvents = _uiEventChannel.receiveAsFlow() + + fun emitEvent(event: UiEvent) { + viewModelScope.launch { _uiEventChannel.send(event) } + } val mealsState: StateFlow = repository.observeMeals() .map, MealsUiState> { meals -> @@ -87,6 +118,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { initialValue = MealsUiState.Loading ) + // Asynchronous background computation of WeeklyStats via Dispatchers.Default + val weeklyStats: StateFlow = repository.observeMeals() + .map { meals -> computeWeeklyStats(meals) } + .flowOn(Dispatchers.Default) + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000L), + initialValue = WeeklyStats.empty() + ) + val customFoods: StateFlow> = repository.observeCustomFoods() .catch { error -> val firestoreError = generateSequence(error) { it.cause } @@ -104,8 +145,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { private val _themeMode = MutableStateFlow(AppThemeMode.DARK) val themeMode: StateFlow = _themeMode.asStateFlow() - private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application) - private val _sheetsUiState = MutableStateFlow( if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) { GoogleSheetsUiState.Success( @@ -170,7 +209,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { satietyAfter: Int, note: String, foodItems: List, - photosBase64: List, + photoUris: List = emptyList(), + photosBase64: List = emptyList(), onSuccess: () -> Unit = {}, onError: (String) -> Unit = {} ) { @@ -183,14 +223,34 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { satietyAfter = satietyAfter.coerceIn(1, 10), note = note.trim(), foodItemsSerialized = foodItems.map { it.serialize() }.take(30), - photosBase64 = photosBase64 + photoUris = photoUris.ifEmpty { photosBase64 }, + photosBase64 = emptyList() ) val result = repository.addMeal(entry) if (result.isSuccess) { onSuccess() + emitEvent(UiEvent.ShowSnackbar("Repas enregistré avec succès ✨")) triggerAutoSheetsSyncIfNeeded() } else { - onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement") + val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement" + onError(err) + emitEvent(UiEvent.ShowSnackbar(err)) + } + } + } + + fun signOut(context: Context, onComplete: () -> Unit = {}) { + viewModelScope.launch { + try { + FirebaseAuth.getInstance().signOut() + val credManager = androidx.credentials.CredentialManager.create(context) + credManager.clearCredentialState(androidx.credentials.ClearCredentialStateRequest()) + } catch (e: Exception) { + if (e is CancellationException) throw e + } finally { + disconnectGoogleSheets() + onComplete() + emitEvent(UiEvent.ShowSnackbar("Mode local actif • Déconnecté")) } } } @@ -211,9 +271,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { val result = repository.updateMeal(sanitizedMeal) if (result.isSuccess) { onSuccess() + emitEvent(UiEvent.ShowSnackbar("Repas mis à jour ✨")) triggerAutoSheetsSyncIfNeeded() } else { - onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour") + val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour" + onError(err) + emitEvent(UiEvent.ShowSnackbar(err)) } } } @@ -227,9 +290,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { val result = repository.deleteMeal(mealId) if (result.isSuccess) { onSuccess() + emitEvent(UiEvent.ShowSnackbar("Repas supprimé")) triggerAutoSheetsSyncIfNeeded() } else { - onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression") + val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression" + onError(err) + emitEvent(UiEvent.ShowSnackbar(err)) } } } @@ -237,26 +303,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { private fun triggerAutoSheetsSyncIfNeeded() { if (!sheetsPrefs.isAutoSyncEnabled) return viewModelScope.launch { - try { - val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context) - val token = tokenResult.getOrNull() ?: return@launch - val sheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) - val (id, url) = sheetResult.getOrNull() ?: return@launch - sheetsPrefs.spreadsheetId = id - sheetsPrefs.spreadsheetUrl = url - _spreadsheetUrl.value = url - - val currentMeals = repository.getAllMealsSnapshot() - val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) - if (syncResult.isSuccess) { - val res = syncResult.getOrThrow() - sheetsPrefs.lastSyncTimestamp = res.timestamp - sheetsPrefs.lastSyncCount = res.mealsCount - sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement" - _sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp) - } - } catch (_: Exception) { - // Non-blocking background sync + sheetsSyncUseCase.executeAutoSyncQuietly()?.let { res -> + _spreadsheetUrl.value = res.spreadsheetUrl + _sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp) } } } @@ -267,51 +316,22 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { ) { viewModelScope.launch { _sheetsUiState.value = GoogleSheetsUiState.Syncing - val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context) - if (tokenResult.isFailure) { - val exception = tokenResult.exceptionOrNull() - if (exception is UserRecoverableAuthException) { - val intent = exception.intent - _sheetsUiState.value = GoogleSheetsUiState.Error( - "Autorisation requise pour Google Sheets & Drive", - recoverableIntent = intent - ) - onError("Autorisation requise pour Google Sheets & Drive", intent) - } else { - val msg = exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google" - _sheetsUiState.value = GoogleSheetsUiState.Error(msg) - onError(msg, null) + when (val result = sheetsSyncUseCase.execute()) { + is SheetsSyncResult.Success -> { + _spreadsheetUrl.value = result.url + _sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp) + onSuccess(result.url, result.count) + emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊")) + } + is SheetsSyncResult.RecoverableAuth -> { + _sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent) + onError(result.message, result.intent) + } + is SheetsSyncResult.Failure -> { + _sheetsUiState.value = GoogleSheetsUiState.Error(result.message) + onError(result.message, null) + emitEvent(UiEvent.ShowSnackbar(result.message)) } - return@launch - } - - val token = tokenResult.getOrThrow() - val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) - if (spreadsheetResult.isFailure) { - val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création de la feuille" - _sheetsUiState.value = GoogleSheetsUiState.Error(err) - onError(err, null) - return@launch - } - - val (id, url) = spreadsheetResult.getOrThrow() - sheetsPrefs.spreadsheetId = id - sheetsPrefs.spreadsheetUrl = url - _spreadsheetUrl.value = url - - val currentMeals = repository.getAllMealsSnapshot() - val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) - if (syncResult.isSuccess) { - val res = syncResult.getOrThrow() - sheetsPrefs.lastSyncTimestamp = res.timestamp - sheetsPrefs.lastSyncCount = res.mealsCount - sheetsPrefs.lastSyncStatus = "Synchronisé avec succès" - _sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp) - onSuccess(res.spreadsheetUrl, res.mealsCount) - } else { - val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas" - _sheetsUiState.value = GoogleSheetsUiState.Error(err) - onError(err, null) } } } @@ -323,24 +343,47 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { onError: (String) -> Unit ) { viewModelScope.launch { - val result = CsvExporter.writeCsvToUri(context, targetUri, meals) + val result = csvExportUseCase.writeToUri(targetUri, meals) result.fold( - onSuccess = { count -> onSuccess(count) }, - onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'export CSV") } + onSuccess = { count -> + onSuccess(count) + emitEvent(UiEvent.ShowSnackbar("Fichier CSV enregistré ($count repas) ✨")) + }, + onFailure = { err -> + val msg = err.localizedMessage ?: "Erreur lors de l'export CSV" + onError(msg) + emitEvent(UiEvent.ShowSnackbar(msg)) + } ) } } fun importCsvFromUri( sourceUri: Uri, - onSuccess: (com.example.util.CsvImportResult) -> Unit, + onSuccess: (CsvImportResult) -> Unit, onError: (String) -> Unit ) { viewModelScope.launch { val result = repository.importMealsFromCsv(context, sourceUri) result.fold( - onSuccess = { importResult -> onSuccess(importResult) }, - onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'import du fichier CSV") } + onSuccess = { importResult -> + onSuccess(importResult) + val count = importResult.importedMeals.size + val skipped = importResult.skippedDuplicatesCount + val newFoods = importResult.newFoodItems.size + val msg = buildString { + append("$count repas importé${if (count > 1) "s" else ""}") + if (skipped > 0) append(" ($skipped doublon${if (skipped > 1) "s" else ""} ignoré${if (skipped > 1) "s" else ""})") + if (newFoods > 0) append(" • $newFoods nouvel aliment ajouté") + append(" ✨") + } + emitEvent(UiEvent.ShowSnackbar(msg)) + }, + onFailure = { err -> + val msg = err.localizedMessage ?: "Erreur lors de l'import du fichier CSV" + onError(msg) + emitEvent(UiEvent.ShowSnackbar(msg)) + } ) } } @@ -352,8 +395,15 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { viewModelScope.launch { val result = repository.syncCloudToLocal() result.fold( - onSuccess = { count -> onSuccess(count) }, - onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de la synchronisation") } + onSuccess = { count -> + onSuccess(count) + emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️")) + }, + onFailure = { err -> + val msg = err.localizedMessage ?: "Erreur lors de la synchronisation" + onError(msg) + emitEvent(UiEvent.ShowSnackbar(msg)) + } ) } } @@ -365,10 +415,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { onError: (String) -> Unit ) { viewModelScope.launch { - val result = CsvExporter.shareCsvFile(activityContext, meals) + val result = csvExportUseCase.createShareIntent(activityContext, meals) result.fold( - onSuccess = { chooserIntent -> onIntentReady(chooserIntent) }, - onFailure = { err -> onError(err.localizedMessage ?: "Impossible de préparer le partage CSV") } + onSuccess = { chooserIntent -> + onIntentReady(chooserIntent) + }, + onFailure = { err -> + val msg = err.localizedMessage ?: "Impossible de préparer le partage CSV" + onError(msg) + emitEvent(UiEvent.ShowSnackbar(msg)) + } ) } } @@ -390,85 +446,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { fun triggerTestNotification(mealType: MealType) { MealNotificationManager.showMealNotification(context, mealType) + emitEvent(UiEvent.ShowSnackbar("Notification de rappel envoyée !")) } - fun computeWeeklyStats(meals: List): WeeklyStats { - val now = System.currentTimeMillis() - val sevenDaysAgo = now - (7L * 24 * 60 * 60 * 1000) - - val endOfToday = Calendar.getInstance().apply { - set(Calendar.HOUR_OF_DAY, 23) - set(Calendar.MINUTE, 59) - set(Calendar.SECOND, 59) - set(Calendar.MILLISECOND, 999) - }.timeInMillis - - val recentMeals = meals.filter { it.mealTimestamp in sevenDaysAgo..endOfToday } - - val dayFormat = SimpleDateFormat("EEE", Locale.FRENCH) - val fullDayFormat = SimpleDateFormat("d MMM", Locale.FRENCH) - - val daysList = mutableListOf() - - for (i in 6 downTo 0) { - val dayCal = Calendar.getInstance().apply { - timeInMillis = now - add(Calendar.DAY_OF_YEAR, -i) - set(Calendar.HOUR_OF_DAY, 0) - set(Calendar.MINUTE, 0) - set(Calendar.SECOND, 0) - set(Calendar.MILLISECOND, 0) - } - val startOfDay = dayCal.timeInMillis - val endOfDay = startOfDay + (24 * 60 * 60 * 1000) - 1 - - val dayMeals = meals.filter { it.mealTimestamp in startOfDay..endOfDay } - - val avgSatiety = if (dayMeals.isNotEmpty()) { - dayMeals.map { it.satietyAfter }.average().toFloat() - } else 0f - - val avgHunger = if (dayMeals.isNotEmpty()) { - dayMeals.map { it.hungerBefore }.average().toFloat() - } else 0f - - daysList.add( - DayStat( - dayLabel = fullDayFormat.format(dayCal.time), - dayShortName = dayFormat.format(dayCal.time).replace(".", "").replaceFirstChar { - if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() - }, - timestampMillis = startOfDay, - avgSatiety = avgSatiety, - avgHunger = avgHunger, - mealCount = dayMeals.size - ) - ) - } - - val allRecentSatieties = recentMeals.map { it.satietyAfter } - val allRecentHungers = recentMeals.map { it.hungerBefore } - - val avgSatiety = if (allRecentSatieties.isNotEmpty()) allRecentSatieties.average().toFloat() else 0f - val avgHunger = if (allRecentHungers.isNotEmpty()) allRecentHungers.average().toFloat() else 0f - - val optimalCount = recentMeals.count { it.satietyAfter in 6..8 } - val optimalPercentage = if (recentMeals.isNotEmpty()) { - ((optimalCount.toFloat() / recentMeals.size) * 100).toInt() - } else 0 - - val distribution = mutableMapOf() - MealType.entries.forEach { type -> - distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) } - } - - return WeeklyStats( - dailyStats = daysList, - averageSatiety = avgSatiety, - averageHunger = avgHunger, - optimalZonePercentage = optimalPercentage, - totalMealsLast7Days = recentMeals.size, - mealTypeDistribution = distribution - ) + fun computeWeeklyStats(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { + return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId) } } diff --git a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt index e88d9ca..a10314e 100644 --- a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt +++ b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt @@ -1,67 +1,33 @@ package com.example.ui.meal -import android.graphics.Bitmap import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.LazyRow -import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -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.AddAPhoto -import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.RestaurantMenu -import androidx.compose.material.icons.filled.Scale -import androidx.compose.material.icons.filled.Schedule -import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.DatePicker -import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Slider -import androidx.compose.material3.SliderDefaults -import androidx.compose.material3.SuggestionChip -import androidx.compose.material3.SuggestionChipDefaults -import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TimePicker -import androidx.compose.material3.rememberDatePickerState import androidx.compose.material3.rememberModalBottomSheetState -import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -70,36 +36,30 @@ import androidx.compose.runtime.mutableStateListOf 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.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.example.data.model.CustomFoodEntry import com.example.data.model.DefaultFoodCatalog import com.example.data.model.FoodUnit -import com.example.data.model.HungerSatietyScale import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType +import com.example.ui.meal.components.FoodItemBuilderSection +import com.example.ui.meal.components.MealDateTimePicker +import com.example.ui.meal.components.MealHungerSatietySection +import com.example.ui.meal.components.MealPhotosSection +import com.example.ui.meal.components.MealTypeSelector import com.example.util.ImageUtils import kotlinx.coroutines.launch -import java.text.SimpleDateFormat -import java.util.Calendar -import java.util.Date import java.util.Locale -import java.util.TimeZone -import kotlin.math.roundToInt -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@OptIn(ExperimentalMaterial3Api::class) @Composable fun MealEntrySheet( initialMeal: MealEntry? = null, @@ -113,21 +73,22 @@ fun MealEntrySheet( val context = LocalContext.current val coroutineScope = rememberCoroutineScope() - var selectedType by remember { + var selectedType by rememberSaveable { mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType) } - var mealTimestamp by remember { + var mealTimestamp by rememberSaveable { mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis()) } - var hungerLevel by remember { + var hungerLevel by rememberSaveable { mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10)) } - var satietyLevel by remember { + var satietyLevel by rememberSaveable { mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10)) } - var globalNoteText by remember { + var globalNoteText by rememberSaveable { mutableStateOf(initialMeal?.note ?: "") } + val foodItemsList = remember { mutableStateListOf().apply { if (initialMeal != null) { @@ -135,18 +96,18 @@ fun MealEntrySheet( } } } - val photosBase64List = remember { + val photoUrisList = remember { mutableStateListOf().apply { if (initialMeal != null) { - addAll(initialMeal.photosBase64) + addAll(initialMeal.displayPhotoUris) } } } - // Current food builder state - var foodNameInput by remember { mutableStateOf("") } - var foodWeightInput by remember { mutableStateOf("") } - var selectedFoodUnit by remember { mutableStateOf(FoodUnit.G) } + // Current food builder input state + var foodNameInput by rememberSaveable { mutableStateOf("") } + var foodWeightInput by rememberSaveable { mutableStateOf("") } + var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) } // Combine custom foods (user enriched) + built-in catalog val mergedCatalog = remember(customFoods) { @@ -190,7 +151,6 @@ fun MealEntrySheet( weight = parsedWeight, unit = selectedFoodUnit ) - // Replace if same food already added, or append val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) } if (existingIndex >= 0) { foodItemsList[existingIndex] = newItem @@ -207,8 +167,6 @@ fun MealEntrySheet( } var isProcessingPhoto by remember { mutableStateOf(false) } - var showDatePicker by remember { mutableStateOf(false) } - var showTimePicker by remember { mutableStateOf(false) } val photoPickerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia() @@ -216,18 +174,15 @@ fun MealEntrySheet( if (uri != null) { isProcessingPhoto = true coroutineScope.launch { - val b64 = ImageUtils.uriToBase64(context, uri) - if (b64 != null && photosBase64List.size < 4) { - photosBase64List.add(b64) + val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri) + if (savedUri != null && photoUrisList.size < 4) { + photoUrisList.add(savedUri) } isProcessingPhoto = false } } } - val dateFormat = remember { SimpleDateFormat("EEE d MMM yyyy", Locale.FRENCH) } - val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.FRENCH) } - ModalBottomSheet( onDismissRequest = onDismiss, sheetState = sheetState, @@ -273,518 +228,77 @@ fun MealEntrySheet( Spacer(modifier = Modifier.height(16.dp)) - // Meal Type Chips - Text( - text = "Type de repas", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary + // Subcomponent 1: Meal Type Chips + MealTypeSelector( + selectedType = selectedType, + onTypeSelected = { selectedType = it } ) - Spacer(modifier = Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - MealType.entries.forEach { type -> - val isSelected = selectedType == type - FilterChip( - selected = isSelected, - onClick = { selectedType = type }, - label = { - Text( - text = type.displayName, - style = MaterialTheme.typography.labelMedium - ) - }, - colors = FilterChipDefaults.filterChipColors( - selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, - selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer - ) - ) - } - } Spacer(modifier = Modifier.height(16.dp)) - // Date & Time Picker Section - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = "Date et heure du repas", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary - ) - - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text( - text = "Maintenant", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.secondary, - modifier = Modifier - .clip(RoundedCornerShape(6.dp)) - .clickable { mealTimestamp = System.currentTimeMillis() } - .padding(horizontal = 6.dp, vertical = 2.dp) - ) - Text( - text = "Hier", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.secondary, - modifier = Modifier - .clip(RoundedCornerShape(6.dp)) - .clickable { - val cal = Calendar.getInstance().apply { - timeInMillis = mealTimestamp - add(Calendar.DAY_OF_YEAR, -1) - } - mealTimestamp = cal.timeInMillis - } - .padding(horizontal = 6.dp, vertical = 2.dp) - ) - } - } - - Spacer(modifier = Modifier.height(8.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(10.dp) - ) { - OutlinedButton( - onClick = { showDatePicker = true }, - modifier = Modifier - .weight(1.3f) - .testTag("edit_date_button"), - shape = RoundedCornerShape(12.dp) - ) { - Icon( - imageVector = Icons.Default.CalendarMonth, - contentDescription = "Changer la date", - modifier = Modifier.size(18.dp), - tint = MaterialTheme.colorScheme.primary - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = dateFormat.format(Date(mealTimestamp)).replaceFirstChar { - if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() - }, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface - ) - } - - OutlinedButton( - onClick = { showTimePicker = true }, - modifier = Modifier - .weight(0.9f) - .testTag("edit_time_button"), - shape = RoundedCornerShape(12.dp) - ) { - Icon( - imageVector = Icons.Default.Schedule, - contentDescription = "Changer l'heure", - modifier = Modifier.size(18.dp), - tint = MaterialTheme.colorScheme.primary - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = timeFormat.format(Date(mealTimestamp)), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface - ) - } - } + // Subcomponent 2: Date & Time Picker + MealDateTimePicker( + mealTimestamp = mealTimestamp, + onTimestampChanged = { mealTimestamp = it } + ) Spacer(modifier = Modifier.height(20.dp)) - // Photos Section - Text( - text = "Photos de l'assiette (${photosBase64List.size}/4)", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary - ) - Spacer(modifier = Modifier.height(8.dp)) - - LazyRow( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically - ) { - if (photosBase64List.size < 4) { - item { - Surface( - modifier = Modifier - .size(84.dp) - .clip(RoundedCornerShape(14.dp)) - .border( - width = 1.dp, - color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f), - shape = RoundedCornerShape(14.dp) - ) - .clickable(enabled = !isProcessingPhoto) { - photoPickerLauncher.launch( - PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) - ) - } - .testTag("add_photo_button"), - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f) - ) { - Box(contentAlignment = Alignment.Center) { - if (isProcessingPhoto) { - CircularProgressIndicator( - modifier = Modifier.size(24.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.primary - ) - } else { - Column(horizontalAlignment = Alignment.CenterHorizontally) { - Icon( - imageVector = Icons.Default.AddAPhoto, - contentDescription = "Ajouter une photo", - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier.size(24.dp) - ) - Spacer(modifier = Modifier.height(4.dp)) - Text( - text = "Ajouter", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - } - } - } + // Subcomponent 3: Photos Section + MealPhotosSection( + photoUris = photoUrisList, + isProcessingPhoto = isProcessingPhoto, + onAddPhotoClick = { + photoPickerLauncher.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + }, + onDeletePhotoClick = { photoUri -> + ImageUtils.deletePhotoFile(photoUri) + photoUrisList.remove(photoUri) } - - items(photosBase64List) { b64 -> - val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) } - Box( - modifier = Modifier - .size(84.dp) - .clip(RoundedCornerShape(14.dp)) - ) { - if (bitmap != null) { - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = "Photo assiette", - modifier = Modifier.matchParentSize(), - contentScale = ContentScale.Crop - ) - } else { - Box( - modifier = Modifier - .matchParentSize() - .background(MaterialTheme.colorScheme.surfaceVariant) - ) - } - - Surface( - modifier = Modifier - .align(Alignment.TopEnd) - .padding(4.dp) - .size(22.dp) - .clip(CircleShape) - .clickable { photosBase64List.remove(b64) }, - color = Color.Black.copy(alpha = 0.7f) - ) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = "Supprimer photo", - tint = Color.White, - modifier = Modifier.padding(2.dp) - ) - } - } - } - } - - Spacer(modifier = Modifier.height(22.dp)) - - // 1. Hunger Stepped Slider (1 to 10) - SteppedScaleTenSlider( - title = "1. Faim avant le repas", - currentValue = hungerLevel, - accentColor = MaterialTheme.colorScheme.secondary, - onValueChange = { hungerLevel = it }, - description = HungerSatietyScale.getHungerLabel(hungerLevel), - sliderTag = "hunger_slider_10" - ) - - Spacer(modifier = Modifier.height(18.dp)) - - // 2. Satiety Stepped Slider (1 to 10) - SteppedScaleTenSlider( - title = "2. Satiété après le repas", - currentValue = satietyLevel, - accentColor = MaterialTheme.colorScheme.primary, - onValueChange = { satietyLevel = it }, - description = HungerSatietyScale.getSatietyLabel(satietyLevel), - sliderTag = "satiety_slider_10" ) Spacer(modifier = Modifier.height(22.dp)) - // 3. Enrichable Food List + Optional Weight Section - Surface( - shape = RoundedCornerShape(18.dp), - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), - modifier = Modifier.fillMaxWidth() - ) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Icon( - imageVector = Icons.Default.RestaurantMenu, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier.size(18.dp) - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = "3. Aliments & Poids (optionnel)", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurface - ) - } + // Subcomponent 4: Hunger & Satiety Sliders (1 to 10) + MealHungerSatietySection( + hungerLevel = hungerLevel, + satietyLevel = satietyLevel, + onHungerChange = { hungerLevel = it }, + onSatietyChange = { satietyLevel = it } + ) - Text( - text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.SemiBold - ) - } + Spacer(modifier = Modifier.height(22.dp)) - Spacer(modifier = Modifier.height(4.dp)) - - Text( - text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Spacer(modifier = Modifier.height(10.dp)) - - // Auto-complete / Quick suggestions row - if (matchingSuggestions.isNotEmpty()) { - LazyRow( - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - items(matchingSuggestions, key = { it.name }) { suggestion -> - SuggestionChip( - onClick = { - foodNameInput = suggestion.name - selectedFoodUnit = suggestion.defaultUnit - }, - label = { - Text( - text = "${suggestion.name} (${suggestion.defaultUnit.label})", - style = MaterialTheme.typography.labelSmall - ) - }, - colors = SuggestionChipDefaults.suggestionChipColors( - containerColor = MaterialTheme.colorScheme.surface, - labelColor = MaterialTheme.colorScheme.onSurface - ) - ) - } - } - Spacer(modifier = Modifier.height(10.dp)) - } - - // Food Name Input - OutlinedTextField( - value = foodNameInput, - onValueChange = { if (it.length <= 80) foodNameInput = it }, - modifier = Modifier - .fillMaxWidth() - .testTag("food_name_input"), - placeholder = { - Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)") - }, - singleLine = true, - shape = RoundedCornerShape(12.dp), - trailingIcon = { - if (foodNameInput.isNotEmpty()) { - IconButton(onClick = { foodNameInput = "" }) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = "Effacer", - modifier = Modifier.size(18.dp) - ) - } - } - } - ) - - if (isNewCustomFood) { - Spacer(modifier = Modifier.height(4.dp)) - Text( - text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.secondary - ) - } - - Spacer(modifier = Modifier.height(10.dp)) - - // Optional Weight + Unit Selector + Add Button - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - OutlinedTextField( - value = foodWeightInput, - onValueChange = { input -> - if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) { - foodWeightInput = input - } - }, - modifier = Modifier - .weight(1f) - .testTag("food_weight_input"), - placeholder = { - Text("Poids opt.") - }, - leadingIcon = { - Icon( - imageVector = Icons.Default.Scale, - contentDescription = null, - modifier = Modifier.size(16.dp), - tint = MaterialTheme.colorScheme.primary - ) - }, - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), - shape = RoundedCornerShape(12.dp) - ) - - // Unit Selector Chips (g, ml, portion) - Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { - FoodUnit.entries.forEach { unit -> - val isUnitSelected = selectedFoodUnit == unit - FilterChip( - selected = isUnitSelected, - onClick = { selectedFoodUnit = unit }, - label = { - Text( - text = unit.label, - style = MaterialTheme.typography.labelSmall - ) - }, - colors = FilterChipDefaults.filterChipColors( - selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, - selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer - ) - ) - } - } - } - - Spacer(modifier = Modifier.height(10.dp)) - - Button( - onClick = { addCurrentFoodItem() }, - enabled = foodNameInput.trim().isNotEmpty(), - modifier = Modifier - .fillMaxWidth() - .testTag("add_food_item_button"), - shape = RoundedCornerShape(12.dp), - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.primaryContainer, - contentColor = MaterialTheme.colorScheme.onPrimaryContainer - ) - ) { - Icon( - imageVector = Icons.Default.Add, - contentDescription = null, - modifier = Modifier.size(18.dp) - ) - Spacer(modifier = Modifier.width(6.dp)) - Text( - text = if (foodWeightInput.isNotBlank()) { - "Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})" - } else { - "Ajouter à l'assiette (sans poids)" - }, - style = MaterialTheme.typography.labelLarge - ) - } - - // Added food items badges - if (foodItemsList.isNotEmpty()) { - Spacer(modifier = Modifier.height(14.dp)) - Text( - text = "Aliments dans l'assiette (touchez pour modifier le poids) :", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Spacer(modifier = Modifier.height(8.dp)) - - FlowRow( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - foodItemsList.forEach { item -> - Surface( - shape = RoundedCornerShape(12.dp), - color = MaterialTheme.colorScheme.surface, - modifier = Modifier - .clip(RoundedCornerShape(12.dp)) - .clickable { - // Load back into inputs for quick weight edit - foodNameInput = item.name - foodWeightInput = item.weight?.let { - if (it % 1.0 == 0.0) it.toInt().toString() else it.toString() - } ?: "" - selectedFoodUnit = item.unit - foodItemsList.remove(item) - } - ) { - Row( - modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = item.displayBadge(), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.SemiBold - ) - Spacer(modifier = Modifier.width(6.dp)) - Icon( - imageVector = Icons.Default.Close, - contentDescription = "Retirer ${item.name}", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .size(18.dp) - .clip(CircleShape) - .clickable { foodItemsList.remove(item) } - .padding(2.dp) - ) - } - } - } - } - } + // Subcomponent 5: Food items builder & flow-row chips + FoodItemBuilderSection( + foodItemsList = foodItemsList, + matchingSuggestions = matchingSuggestions, + foodNameInput = foodNameInput, + onFoodNameChange = { foodNameInput = it }, + foodWeightInput = foodWeightInput, + onFoodWeightChange = { foodWeightInput = it }, + selectedFoodUnit = selectedFoodUnit, + onFoodUnitSelected = { selectedFoodUnit = it }, + isNewCustomFood = isNewCustomFood, + onAddFoodItem = { addCurrentFoodItem() }, + onItemClickForEdit = { item -> + foodNameInput = item.name + foodWeightInput = item.weight?.let { + if (it % 1.0 == 0.0) it.toInt().toString() else it.toString() + } ?: "" + selectedFoodUnit = item.unit + foodItemsList.remove(item) + }, + onRemoveFoodItem = { item -> + foodItemsList.remove(item) } - } + ) Spacer(modifier = Modifier.height(20.dp)) - // 4. Global Note Field + // Global Note Field Text( text = "4. Note globale du repas (optionnel)", style = MaterialTheme.typography.labelLarge, @@ -827,7 +341,6 @@ fun MealEntrySheet( Spacer(modifier = Modifier.width(10.dp)) Button( onClick = { - // Automatically commit any pending typed food name so user input is never lost if (foodNameInput.trim().isNotEmpty()) { addCurrentFoodItem() } @@ -838,7 +351,7 @@ fun MealEntrySheet( satietyLevel.coerceIn(1, 10), globalNoteText, foodItemsList.toList(), - photosBase64List.toList() + photoUrisList.toList() ) }, modifier = Modifier @@ -860,189 +373,4 @@ fun MealEntrySheet( Spacer(modifier = Modifier.height(16.dp)) } } - - // Material 3 DatePickerDialog - if (showDatePicker) { - val datePickerState = rememberDatePickerState( - initialSelectedDateMillis = mealTimestamp - ) - DatePickerDialog( - onDismissRequest = { showDatePicker = false }, - confirmButton = { - TextButton( - onClick = { - val selectedUtcMillis = datePickerState.selectedDateMillis - if (selectedUtcMillis != null) { - val utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { - timeInMillis = selectedUtcMillis - } - val localCal = Calendar.getInstance().apply { - timeInMillis = mealTimestamp - set(Calendar.YEAR, utcCal.get(Calendar.YEAR)) - set(Calendar.MONTH, utcCal.get(Calendar.MONTH)) - set(Calendar.DAY_OF_MONTH, utcCal.get(Calendar.DAY_OF_MONTH)) - } - mealTimestamp = localCal.timeInMillis - } - showDatePicker = false - }, - modifier = Modifier.testTag("confirm_date_button") - ) { - Text("Valider la date") - } - }, - dismissButton = { - TextButton(onClick = { showDatePicker = false }) { - Text("Annuler") - } - } - ) { - DatePicker(state = datePickerState) - } - } - - // Material 3 TimePicker Dialog - if (showTimePicker) { - val currentCal = remember(mealTimestamp) { - Calendar.getInstance().apply { timeInMillis = mealTimestamp } - } - val timePickerState = rememberTimePickerState( - initialHour = currentCal.get(Calendar.HOUR_OF_DAY), - initialMinute = currentCal.get(Calendar.MINUTE), - is24Hour = true - ) - AlertDialog( - onDismissRequest = { showTimePicker = false }, - title = { Text("Modifier l'heure du repas") }, - text = { - Box( - modifier = Modifier.fillMaxWidth(), - contentAlignment = Alignment.Center - ) { - TimePicker(state = timePickerState) - } - }, - confirmButton = { - TextButton( - onClick = { - val updatedCal = Calendar.getInstance().apply { - timeInMillis = mealTimestamp - set(Calendar.HOUR_OF_DAY, timePickerState.hour) - set(Calendar.MINUTE, timePickerState.minute) - set(Calendar.SECOND, 0) - } - mealTimestamp = updatedCal.timeInMillis - showTimePicker = false - }, - modifier = Modifier.testTag("confirm_time_button") - ) { - Text("Valider l'heure") - } - }, - dismissButton = { - TextButton(onClick = { showTimePicker = false }) { - Text("Annuler") - } - } - ) - } -} - -@Composable -private fun SteppedScaleTenSlider( - title: String, - currentValue: Int, - accentColor: Color, - onValueChange: (Int) -> Unit, - description: String, - sliderTag: String -) { - Surface( - shape = RoundedCornerShape(18.dp), - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), - modifier = Modifier.fillMaxWidth() - ) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 14.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = title, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurface - ) - - Surface( - shape = RoundedCornerShape(10.dp), - color = accentColor.copy(alpha = 0.2f) - ) { - Text( - text = "$currentValue / 10", - style = MaterialTheme.typography.titleMedium, - color = accentColor, - fontWeight = FontWeight.Bold, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp) - ) - } - } - - Spacer(modifier = Modifier.height(6.dp)) - - Text( - text = description, - style = MaterialTheme.typography.bodySmall, - color = accentColor, - fontWeight = FontWeight.Medium - ) - - Spacer(modifier = Modifier.height(4.dp)) - - Slider( - value = currentValue.toFloat(), - onValueChange = { newValue -> - onValueChange(newValue.roundToInt().coerceIn(1, 10)) - }, - valueRange = 1f..10f, - steps = 8, - colors = SliderDefaults.colors( - thumbColor = accentColor, - activeTrackColor = accentColor, - inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant, - activeTickColor = MaterialTheme.colorScheme.surface, - inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f) - ), - modifier = Modifier - .fillMaxWidth() - .testTag(sliderTag) - ) - - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 4.dp), - horizontalArrangement = Arrangement.SpaceBetween - ) { - (1..10).forEach { num -> - val isSelected = num == currentValue - Text( - text = num.toString(), - style = MaterialTheme.typography.labelSmall, - fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, - color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - modifier = Modifier - .clip(CircleShape) - .clickable { onValueChange(num) } - .padding(horizontal = 4.dp, vertical = 2.dp) - ) - } - } - } - } } diff --git a/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt b/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt new file mode 100644 index 0000000..1a3b264 --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt @@ -0,0 +1,313 @@ +package com.example.ui.meal.components + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.RestaurantMenu +import androidx.compose.material.icons.filled.Scale +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SuggestionChip +import androidx.compose.material3.SuggestionChipDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import com.example.data.model.DefaultFoodCatalog +import com.example.data.model.FoodUnit +import com.example.data.model.MealFoodItem + +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun FoodItemBuilderSection( + foodItemsList: List, + matchingSuggestions: List, + foodNameInput: String, + onFoodNameChange: (String) -> Unit, + foodWeightInput: String, + onFoodWeightChange: (String) -> Unit, + selectedFoodUnit: FoodUnit, + onFoodUnitSelected: (FoodUnit) -> Unit, + isNewCustomFood: Boolean, + onAddFoodItem: () -> Unit, + onItemClickForEdit: (MealFoodItem) -> Unit, + onRemoveFoodItem: (MealFoodItem) -> Unit, + modifier: Modifier = Modifier +) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), + modifier = modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Default.RestaurantMenu, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "3. Aliments & Poids (optionnel)", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Text( + text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + Text( + text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(10.dp)) + + // Auto-complete / Quick suggestions row + if (matchingSuggestions.isNotEmpty()) { + LazyRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(matchingSuggestions, key = { it.name }) { suggestion -> + SuggestionChip( + onClick = { + onFoodNameChange(suggestion.name) + onFoodUnitSelected(suggestion.defaultUnit) + }, + label = { + Text( + text = "${suggestion.name} (${suggestion.defaultUnit.label})", + style = MaterialTheme.typography.labelSmall + ) + }, + colors = SuggestionChipDefaults.suggestionChipColors( + containerColor = MaterialTheme.colorScheme.surface, + labelColor = MaterialTheme.colorScheme.onSurface + ) + ) + } + } + Spacer(modifier = Modifier.height(10.dp)) + } + + // Food Name Input + OutlinedTextField( + value = foodNameInput, + onValueChange = { if (it.length <= 80) onFoodNameChange(it) }, + modifier = Modifier + .fillMaxWidth() + .testTag("food_name_input"), + placeholder = { + Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)") + }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + trailingIcon = { + if (foodNameInput.isNotEmpty()) { + IconButton(onClick = { onFoodNameChange("") }) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Effacer", + modifier = Modifier.size(18.dp) + ) + } + } + } + ) + + if (isNewCustomFood) { + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.secondary + ) + } + + Spacer(modifier = Modifier.height(10.dp)) + + // Optional Weight + Unit Selector + Add Button + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedTextField( + value = foodWeightInput, + onValueChange = { input -> + if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) { + onFoodWeightChange(input) + } + }, + modifier = Modifier + .weight(1f) + .testTag("food_weight_input"), + placeholder = { + Text("Poids opt.") + }, + leadingIcon = { + Icon( + imageVector = Icons.Default.Scale, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.primary + ) + }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + shape = RoundedCornerShape(12.dp) + ) + + // Unit Selector Chips (g, ml, portion) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + FoodUnit.entries.forEach { unit -> + val isUnitSelected = selectedFoodUnit == unit + FilterChip( + selected = isUnitSelected, + onClick = { onFoodUnitSelected(unit) }, + label = { + Text( + text = unit.label, + style = MaterialTheme.typography.labelSmall + ) + }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, + selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + ) + } + } + } + + Spacer(modifier = Modifier.height(10.dp)) + + Button( + onClick = onAddFoodItem, + enabled = foodNameInput.trim().isNotEmpty(), + modifier = Modifier + .fillMaxWidth() + .testTag("add_food_item_button"), + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = if (foodWeightInput.isNotBlank()) { + "Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})" + } else { + "Ajouter à l'assiette (sans poids)" + }, + style = MaterialTheme.typography.labelLarge + ) + } + + // Added food items badges + if (foodItemsList.isNotEmpty()) { + Spacer(modifier = Modifier.height(14.dp)) + Text( + text = "Aliments dans l'assiette (touchez pour modifier le poids) :", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(8.dp)) + + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + foodItemsList.forEach { item -> + Surface( + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.surface, + modifier = Modifier + .clip(RoundedCornerShape(12.dp)) + .clickable { onItemClickForEdit(item) } + ) { + Row( + modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = item.displayBadge(), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold + ) + Spacer(modifier = Modifier.width(6.dp)) + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Retirer ${item.name}", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .size(18.dp) + .clip(CircleShape) + .clickable { onRemoveFoodItem(item) } + .padding(2.dp) + ) + } + } + } + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/meal/components/MealDateTimePicker.kt b/app/src/main/java/com/example/ui/meal/components/MealDateTimePicker.kt new file mode 100644 index 0000000..747258c --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/MealDateTimePicker.kt @@ -0,0 +1,239 @@ +package com.example.ui.meal.components + +import androidx.compose.foundation.clickable +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.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.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CalendarMonth +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DatePicker +import androidx.compose.material3.DatePickerDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TimePicker +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.material3.rememberTimePickerState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.dp +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.Locale + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MealDateTimePicker( + mealTimestamp: Long, + onTimestampChanged: (Long) -> Unit, + modifier: Modifier = Modifier +) { + var showDatePicker by remember { mutableStateOf(false) } + var showTimePicker by remember { mutableStateOf(false) } + + val zoneId = remember { ZoneId.systemDefault() } + val zonedDateTime = remember(mealTimestamp) { + Instant.ofEpochMilli(mealTimestamp).atZone(zoneId) + } + + val dateFormatter = remember { + DateTimeFormatter.ofPattern("EEE d MMM yyyy", Locale.FRENCH) + } + val timeFormatter = remember { + DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH) + } + + Column(modifier = modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Date et heure du repas", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = "Maintenant", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.secondary, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { onTimestampChanged(System.currentTimeMillis()) } + .padding(horizontal = 6.dp, vertical = 2.dp) + ) + Text( + text = "Hier", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.secondary, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { + val yesterdayMillis = zonedDateTime.minusDays(1).toInstant().toEpochMilli() + onTimestampChanged(yesterdayMillis) + } + .padding(horizontal = 6.dp, vertical = 2.dp) + ) + } + } + + Spacer(modifier = Modifier.height(8.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + OutlinedButton( + onClick = { showDatePicker = true }, + modifier = Modifier + .weight(1.3f) + .testTag("edit_date_button"), + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Default.CalendarMonth, + contentDescription = "Changer la date", + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = dateFormatter.format(zonedDateTime).replaceFirstChar { + if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface + ) + } + + OutlinedButton( + onClick = { showTimePicker = true }, + modifier = Modifier + .weight(0.9f) + .testTag("edit_time_button"), + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Default.Schedule, + contentDescription = "Changer l'heure", + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = timeFormatter.format(zonedDateTime), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface + ) + } + } + } + + // Material 3 DatePickerDialog + if (showDatePicker) { + val datePickerState = rememberDatePickerState( + initialSelectedDateMillis = mealTimestamp + ) + DatePickerDialog( + onDismissRequest = { showDatePicker = false }, + confirmButton = { + TextButton( + onClick = { + val selectedUtcMillis = datePickerState.selectedDateMillis + if (selectedUtcMillis != null) { + // Extract year, month, day from the UTC date picker + val selectedLocalDate = Instant.ofEpochMilli(selectedUtcMillis) + .atZone(ZoneId.of("UTC")) + .toLocalDate() + + val updatedZoned = zonedDateTime + .withYear(selectedLocalDate.year) + .withMonth(selectedLocalDate.monthValue) + .withDayOfMonth(selectedLocalDate.dayOfMonth) + + onTimestampChanged(updatedZoned.toInstant().toEpochMilli()) + } + showDatePicker = false + }, + modifier = Modifier.testTag("confirm_date_button") + ) { + Text("Valider la date") + } + }, + dismissButton = { + TextButton(onClick = { showDatePicker = false }) { + Text("Annuler") + } + } + ) { + DatePicker(state = datePickerState) + } + } + + // Material 3 TimePicker Dialog + if (showTimePicker) { + val timePickerState = rememberTimePickerState( + initialHour = zonedDateTime.hour, + initialMinute = zonedDateTime.minute, + is24Hour = true + ) + AlertDialog( + onDismissRequest = { showTimePicker = false }, + title = { Text("Modifier l'heure du repas") }, + text = { + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + TimePicker(state = timePickerState) + } + }, + confirmButton = { + TextButton( + onClick = { + val updatedZoned = zonedDateTime + .withHour(timePickerState.hour) + .withMinute(timePickerState.minute) + .withSecond(0) + onTimestampChanged(updatedZoned.toInstant().toEpochMilli()) + showTimePicker = false + }, + modifier = Modifier.testTag("confirm_time_button") + ) { + Text("Valider l'heure") + } + }, + dismissButton = { + TextButton(onClick = { showTimePicker = false }) { + Text("Annuler") + } + } + ) + } +} diff --git a/app/src/main/java/com/example/ui/meal/components/MealHungerSatietySection.kt b/app/src/main/java/com/example/ui/meal/components/MealHungerSatietySection.kt new file mode 100644 index 0000000..ed19e5c --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/MealHungerSatietySection.kt @@ -0,0 +1,161 @@ +package com.example.ui.meal.components + +import androidx.compose.foundation.clickable +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.SliderDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.example.data.model.HungerSatietyScale +import kotlin.math.roundToInt + +@Composable +fun MealHungerSatietySection( + hungerLevel: Int, + satietyLevel: Int, + onHungerChange: (Int) -> Unit, + onSatietyChange: (Int) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier = modifier.fillMaxWidth()) { + // 1. Hunger Stepped Slider (1 to 10) + SteppedScaleTenSlider( + title = "1. Faim avant le repas", + currentValue = hungerLevel, + accentColor = MaterialTheme.colorScheme.secondary, + onValueChange = onHungerChange, + description = HungerSatietyScale.getHungerLabel(hungerLevel), + sliderTag = "hunger_slider_10" + ) + + Spacer(modifier = Modifier.height(18.dp)) + + // 2. Satiety Stepped Slider (1 to 10) + SteppedScaleTenSlider( + title = "2. Satiété après le repas", + currentValue = satietyLevel, + accentColor = MaterialTheme.colorScheme.primary, + onValueChange = onSatietyChange, + description = HungerSatietyScale.getSatietyLabel(satietyLevel), + sliderTag = "satiety_slider_10" + ) + } +} + +@Composable +fun SteppedScaleTenSlider( + title: String, + currentValue: Int, + accentColor: Color, + onValueChange: (Int) -> Unit, + description: String, + sliderTag: String, + modifier: Modifier = Modifier +) { + Surface( + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), + modifier = modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = title, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurface + ) + + Surface( + shape = RoundedCornerShape(10.dp), + color = accentColor.copy(alpha = 0.2f) + ) { + Text( + text = "$currentValue / 10", + style = MaterialTheme.typography.titleMedium, + color = accentColor, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp) + ) + } + } + + Spacer(modifier = Modifier.height(6.dp)) + + Text( + text = description, + style = MaterialTheme.typography.bodySmall, + color = accentColor, + fontWeight = FontWeight.Medium + ) + + Spacer(modifier = Modifier.height(4.dp)) + + Slider( + value = currentValue.toFloat(), + onValueChange = { newValue -> + onValueChange(newValue.roundToInt().coerceIn(1, 10)) + }, + valueRange = 1f..10f, + steps = 8, + colors = SliderDefaults.colors( + thumbColor = accentColor, + activeTrackColor = accentColor, + inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant, + activeTickColor = MaterialTheme.colorScheme.surface, + inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f) + ), + modifier = Modifier + .fillMaxWidth() + .testTag(sliderTag) + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween + ) { + (1..10).forEach { num -> + val isSelected = num == currentValue + Text( + text = num.toString(), + style = MaterialTheme.typography.labelSmall, + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, + color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier + .clip(CircleShape) + .clickable { onValueChange(num) } + .padding(horizontal = 4.dp, vertical = 2.dp) + ) + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt b/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt new file mode 100644 index 0000000..9897232 --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt @@ -0,0 +1,133 @@ +package com.example.ui.meal.components + +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +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.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AddAPhoto +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.dp +import coil.compose.AsyncImage + +@Composable +fun MealPhotosSection( + photoUris: List, + isProcessingPhoto: Boolean, + onAddPhotoClick: () -> Unit, + onDeletePhotoClick: (String) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier = modifier.fillMaxWidth()) { + Text( + text = "Photos de l'assiette (${photoUris.size}/4)", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.height(8.dp)) + + LazyRow( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (photoUris.size < 4) { + item { + Surface( + modifier = Modifier + .size(84.dp) + .clip(RoundedCornerShape(14.dp)) + .border( + width = 1.dp, + color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f), + shape = RoundedCornerShape(14.dp) + ) + .clickable(enabled = !isProcessingPhoto) { + onAddPhotoClick() + } + .testTag("add_photo_button"), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f) + ) { + Box(contentAlignment = Alignment.Center) { + if (isProcessingPhoto) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.primary + ) + } else { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon( + imageVector = Icons.Default.AddAPhoto, + contentDescription = "Ajouter une photo", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp) + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Ajouter", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } + } + } + + items(photoUris) { photoUri -> + Box( + modifier = Modifier + .size(84.dp) + .clip(RoundedCornerShape(14.dp)) + ) { + AsyncImage( + model = photoUri, + contentDescription = "Photo de l'assiette", + modifier = Modifier.matchParentSize(), + contentScale = ContentScale.Crop + ) + + Surface( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(4.dp) + .size(22.dp) + .clip(CircleShape) + .clickable { onDeletePhotoClick(photoUri) }, + color = Color.Black.copy(alpha = 0.7f) + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Supprimer photo", + tint = Color.White, + modifier = Modifier.padding(2.dp) + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/meal/components/MealTypeSelector.kt b/app/src/main/java/com/example/ui/meal/components/MealTypeSelector.kt new file mode 100644 index 0000000..68739ad --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/MealTypeSelector.kt @@ -0,0 +1,54 @@ +package com.example.ui.meal.components + +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.example.data.model.MealType + +@Composable +fun MealTypeSelector( + selectedType: MealType, + onTypeSelected: (MealType) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier = modifier.fillMaxWidth()) { + Text( + text = "Type de repas", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + MealType.entries.forEach { type -> + val isSelected = selectedType == type + FilterChip( + selected = isSelected, + onClick = { onTypeSelected(type) }, + label = { + Text( + text = type.displayName, + style = MaterialTheme.typography.labelMedium + ) + }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, + selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + ) + } + } + } +} diff --git a/app/src/main/java/com/example/ui/settings/SettingsScreen.kt b/app/src/main/java/com/example/ui/settings/SettingsScreen.kt index e81304e..8e4b882 100644 --- a/app/src/main/java/com/example/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/example/ui/settings/SettingsScreen.kt @@ -45,8 +45,9 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.sp import com.example.ui.journal.GoogleSheetsUiState -import java.text.SimpleDateFormat -import java.util.Date +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults @@ -357,8 +358,8 @@ fun SettingsScreen( } } is GoogleSheetsUiState.Success -> { - val timeStr = SimpleDateFormat("dd/MM/yyyy à HH:mm", Locale.FRENCH) - .format(Date(sheetsUiState.timestamp)) + val timeStr = DateTimeFormatter.ofPattern("dd/MM/yyyy 'à' HH:mm", Locale.FRENCH) + .format(Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault())) Column( modifier = Modifier .fillMaxWidth() @@ -884,16 +885,7 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(16.dp)) Button( - onClick = { - Firebase.auth.signOut() - CoroutineScope(Dispatchers.IO).launch { - try { - val credManager = CredentialManager.create(context) - credManager.clearCredentialState(ClearCredentialStateRequest()) - } catch (_: Exception) {} - } - onSignOut() - }, + onClick = onSignOut, modifier = Modifier .fillMaxWidth() .testTag("signout_button"), diff --git a/app/src/main/java/com/example/util/CsvExporter.kt b/app/src/main/java/com/example/util/CsvExporter.kt index 2208b8f..8d4b391 100644 --- a/app/src/main/java/com/example/util/CsvExporter.kt +++ b/app/src/main/java/com/example/util/CsvExporter.kt @@ -10,21 +10,24 @@ import com.example.data.model.MealType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File -import java.text.SimpleDateFormat -import java.util.Date +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale object CsvExporter { + private val fileDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.FRENCH) + private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH) + private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH) + fun buildDefaultFileName(): String { - val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(Date()) + val dateStr = fileDateFormatter.format(LocalDate.now()) return "satiea_repas_$dateStr.csv" } - fun generateCsvContent(meals: List): String { - val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH) - val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH) - + fun generateCsvContent(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): String { val sb = StringBuilder() // UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets sb.append('\uFEFF') @@ -32,15 +35,15 @@ object CsvExporter { val sortedMeals = meals.sortedByDescending { it.mealTimestamp } for (meal in sortedMeals) { - val dateObj = Date(meal.mealTimestamp) - val dateStr = dateFormat.format(dateObj) - val timeStr = timeFormat.format(dateObj) + val zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId) + val dateStr = dateFormatter.format(zonedDateTime) + val timeStr = timeFormatter.format(zonedDateTime) val mealTypeLabel = MealType.fromString(meal.mealType).displayName val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore) val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter) val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() } val cleanNote = escapeCsvField(meal.note) - val photoCount = meal.photosBase64.size + val photoCount = meal.displayPhotoUris.size sb.append(escapeCsvField(dateStr)).append(',') sb.append(escapeCsvField(timeStr)).append(',') diff --git a/app/src/main/java/com/example/util/CsvImporter.kt b/app/src/main/java/com/example/util/CsvImporter.kt index dff638a..a509ab7 100644 --- a/app/src/main/java/com/example/util/CsvImporter.kt +++ b/app/src/main/java/com/example/util/CsvImporter.kt @@ -11,9 +11,11 @@ import kotlinx.coroutines.withContext import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader -import java.text.SimpleDateFormat -import java.util.Calendar -import java.util.Date +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale import java.util.UUID @@ -25,17 +27,18 @@ data class CsvImportResult( object CsvImporter { - private val supportedDateFormats = listOf( - SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH), - SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH), - SimpleDateFormat("dd-MM-yyyy", Locale.FRENCH), - SimpleDateFormat("d/M/yyyy", Locale.FRENCH) + private val supportedDatePatterns = listOf( + "dd/MM/yyyy", + "yyyy-MM-dd", + "dd-MM-yyyy", + "d/M/yyyy" ) - private val supportedTimeFormats = listOf( - SimpleDateFormat("HH:mm", Locale.FRENCH), - SimpleDateFormat("H:mm", Locale.FRENCH), - SimpleDateFormat("HH:mm:ss", Locale.FRENCH) + private val supportedTimePatterns = listOf( + "HH:mm", + "H:mm", + "HH:mm:ss", + "H:mm:ss" ) suspend fun importFromUri( @@ -157,36 +160,32 @@ object CsvImporter { return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else "" } - private fun parseTimestamp(dateStr: String, timeStr: String): Long? { + private fun parseTimestamp(dateStr: String, timeStr: String, zoneId: ZoneId = ZoneId.systemDefault()): Long? { if (dateStr.isBlank()) return null - var parsedDate: Date? = null - for (df in supportedDateFormats) { + var parsedLocalDate: LocalDate? = null + for (pattern in supportedDatePatterns) { try { - parsedDate = df.parse(dateStr.trim()) - if (parsedDate != null) break + parsedLocalDate = LocalDate.parse(dateStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH)) + if (parsedLocalDate != null) break } catch (_: Exception) {} } - if (parsedDate == null) return null - - val cal = Calendar.getInstance().apply { time = parsedDate } + if (parsedLocalDate == null) return null + var parsedLocalTime = LocalTime.NOON if (timeStr.isNotBlank()) { - for (tf in supportedTimeFormats) { + for (pattern in supportedTimePatterns) { try { - val parsedTime = tf.parse(timeStr.trim()) - if (parsedTime != null) { - val timeCal = Calendar.getInstance().apply { time = parsedTime } - cal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY)) - cal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE)) - cal.set(Calendar.SECOND, 0) - cal.set(Calendar.MILLISECOND, 0) - break - } + parsedLocalTime = LocalTime.parse(timeStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH)) + break } catch (_: Exception) {} } } - return cal.timeInMillis + + return LocalDateTime.of(parsedLocalDate, parsedLocalTime) + .atZone(zoneId) + .toInstant() + .toEpochMilli() } private fun parseMealType(raw: String): MealType { diff --git a/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt b/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt index 35bb7ff..6d225fa 100644 --- a/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt +++ b/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt @@ -3,8 +3,9 @@ package com.example.util import com.example.data.model.HungerSatietyScale import com.example.data.model.MealEntry import com.example.data.model.MealType -import java.text.SimpleDateFormat -import java.util.Date +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale object GoogleSheetsDataFormatter { @@ -22,10 +23,10 @@ object GoogleSheetsDataFormatter { "Photos jointes" ) - fun formatMealsToRows(meals: List): List> { - val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH) - val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH) + private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH) + private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH) + fun formatMealsToRows(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): List> { val rows = mutableListOf>() // Header row rows.add(HEADERS) @@ -34,15 +35,15 @@ object GoogleSheetsDataFormatter { val sortedMeals = meals.sortedByDescending { it.mealTimestamp } for (meal in sortedMeals) { - val dateObj = Date(meal.mealTimestamp) - val dateStr = dateFormat.format(dateObj) - val timeStr = timeFormat.format(dateObj) + val zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId) + val dateStr = dateFormatter.format(zonedDateTime) + val timeStr = timeFormatter.format(zonedDateTime) val mealTypeLabel = MealType.fromString(meal.mealType).displayName val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore) val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter) val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() } val cleanNote = meal.note.replace("\r\n", " ").replace("\n", " ").trim() - val photosCount = meal.photosBase64.size + val photosCount = meal.displayPhotoUris.size rows.add( listOf( diff --git a/app/src/main/java/com/example/util/ImageUtils.kt b/app/src/main/java/com/example/util/ImageUtils.kt index 8ac787b..8462b48 100644 --- a/app/src/main/java/com/example/util/ImageUtils.kt +++ b/app/src/main/java/com/example/util/ImageUtils.kt @@ -5,72 +5,120 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Base64 +import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream import java.io.InputStream +import java.util.UUID object ImageUtils { - suspend fun uriToBase64(context: Context, uri: Uri, maxWidth: Int = 480, maxHeight: Int = 480): String? = - withContext(Dispatchers.IO) { - try { - var inputStream: InputStream? = context.contentResolver.openInputStream(uri) ?: return@withContext null + private const val TAG = "ImageUtils" + private const val PHOTOS_DIR_NAME = "meal_photos" + private const val MAX_DIMENSION = 960 + private const val JPEG_QUALITY = 80 - // Decode bounds first - val options = BitmapFactory.Options().apply { - inJustDecodeBounds = true - } - BitmapFactory.decodeStream(inputStream, null, options) - inputStream?.close() - - // Calculate inSampleSize - var inSampleSize = 1 - if (options.outHeight > maxHeight || options.outWidth > maxWidth) { - val halfHeight = options.outHeight / 2 - val halfWidth = options.outWidth / 2 - while (halfHeight / inSampleSize >= maxHeight && halfWidth / inSampleSize >= maxWidth) { - inSampleSize *= 2 - } - } - - // Decode actual bitmap - val decodeOptions = BitmapFactory.Options().apply { - this.inSampleSize = inSampleSize - } - inputStream = context.contentResolver.openInputStream(uri) - val originalBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions) - inputStream?.close() - - if (originalBitmap == null) return@withContext null - - // Scale to exact target bounds - val scaledBitmap = if (originalBitmap.width > maxWidth || originalBitmap.height > maxHeight) { - val ratio = minOf( - maxWidth.toFloat() / originalBitmap.width, - maxHeight.toFloat() / originalBitmap.height - ) - val targetW = (originalBitmap.width * ratio).toInt().coerceAtLeast(1) - val targetH = (originalBitmap.height * ratio).toInt().coerceAtLeast(1) - Bitmap.createScaledBitmap(originalBitmap, targetW, targetH, true) - } else { - originalBitmap - } - - val outputStream = ByteArrayOutputStream() - scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream) - val bytes = outputStream.toByteArray() - Base64.encodeToString(bytes, Base64.NO_WRAP) - } catch (e: Exception) { - null + fun getPhotosDirectory(context: Context): File { + return File(context.applicationContext.filesDir, PHOTOS_DIR_NAME).apply { + if (!exists()) { + mkdirs() } } + } + suspend fun saveImageToPrivateStorage( + context: Context, + sourceUri: Uri + ): String? = withContext(Dispatchers.IO) { + try { + var inputStream: InputStream? = context.contentResolver.openInputStream(sourceUri) + ?: return@withContext null + + // 1. Decode bounds + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + } + BitmapFactory.decodeStream(inputStream, null, options) + inputStream?.close() + + // 2. Calculate inSampleSize for memory safety + var inSampleSize = 1 + if (options.outHeight > MAX_DIMENSION || options.outWidth > MAX_DIMENSION) { + val halfHeight = options.outHeight / 2 + val halfWidth = options.outWidth / 2 + while (halfHeight / inSampleSize >= MAX_DIMENSION && halfWidth / inSampleSize >= MAX_DIMENSION) { + inSampleSize *= 2 + } + } + + // 3. Decode actual bitmap + val decodeOptions = BitmapFactory.Options().apply { + this.inSampleSize = inSampleSize + } + inputStream = context.contentResolver.openInputStream(sourceUri) + val decodedBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions) + inputStream?.close() + + if (decodedBitmap == null) return@withContext null + + // 4. Scale to max dimension while preserving aspect ratio + val scaledBitmap = if (decodedBitmap.width > MAX_DIMENSION || decodedBitmap.height > MAX_DIMENSION) { + val ratio = minOf( + MAX_DIMENSION.toFloat() / decodedBitmap.width, + MAX_DIMENSION.toFloat() / decodedBitmap.height + ) + val targetW = (decodedBitmap.width * ratio).toInt().coerceAtLeast(1) + val targetH = (decodedBitmap.height * ratio).toInt().coerceAtLeast(1) + Bitmap.createScaledBitmap(decodedBitmap, targetW, targetH, true).also { + if (it != decodedBitmap) decodedBitmap.recycle() + } + } else { + decodedBitmap + } + + // 5. Write directly to private JPEG file + val targetDir = getPhotosDirectory(context) + val uniqueFileName = "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg" + val targetFile = File(targetDir, uniqueFileName) + + FileOutputStream(targetFile).use { outStream -> + scaledBitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, outStream) + outStream.flush() + } + scaledBitmap.recycle() + + Uri.fromFile(targetFile).toString() + } catch (e: Exception) { + Log.e(TAG, "Error saving image to private storage: ${e.message}", e) + null + } + } + + fun deletePhotoFile(photoUriStr: String?): Boolean { + if (photoUriStr.isNullOrBlank()) return false + return try { + val uri = Uri.parse(photoUriStr) + val path = uri.path + if (path != null) { + val file = File(path) + if (file.exists()) { + file.delete() + } else false + } else false + } catch (e: Exception) { + Log.w(TAG, "Could not delete photo file: ${e.message}") + false + } + } + + // Retained for backward-compatibility if old Base64 entries need temporary conversion fun base64ToBitmap(base64Str: String): Bitmap? { return try { val bytes = Base64.decode(base64Str, Base64.DEFAULT) BitmapFactory.decodeByteArray(bytes, 0, bytes.size) - } catch (e: Exception) { + } catch (_: Exception) { null } } diff --git a/app/src/test/java/com/example/CsvImporterTest.kt b/app/src/test/java/com/example/CsvImporterTest.kt index 90aa29e..82e4295 100644 --- a/app/src/test/java/com/example/CsvImporterTest.kt +++ b/app/src/test/java/com/example/CsvImporterTest.kt @@ -6,10 +6,11 @@ import com.example.data.model.MealFoodItem import com.example.data.model.MealType import com.example.util.CsvImporter import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue import org.junit.Test import java.io.ByteArrayInputStream -import java.text.SimpleDateFormat +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter import java.util.Locale class CsvImporterTest { @@ -57,8 +58,11 @@ class CsvImporterTest { @Test fun testDeduplicationIgnoresExistingMeal() { - val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.FRENCH) - val timestamp = dateFormat.parse("08/11/2026 12:30")!!.time + val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm", Locale.FRENCH) + val timestamp = LocalDateTime.parse("08/11/2026 12:30", formatter) + .atZone(ZoneId.systemDefault()) + .toInstant() + .toEpochMilli() val existingMeal = MealEntry( id = "existing_1", diff --git a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt index 17c6674..cb31103 100644 --- a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt +++ b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt @@ -8,32 +8,35 @@ import com.example.util.GoogleSheetsDataFormatter import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test -import java.util.Calendar +import java.time.LocalDateTime +import java.time.ZoneId class GoogleSheetsDataFormatterTest { + private val testZoneId = ZoneId.of("Europe/Paris") + @Test fun `formatMealsToRows with empty list returns only header row`() { - val rows = GoogleSheetsDataFormatter.formatMealsToRows(emptyList()) + val rows = GoogleSheetsDataFormatter.formatMealsToRows(emptyList(), testZoneId) assertEquals(1, rows.size) assertEquals(GoogleSheetsDataFormatter.HEADERS, rows[0]) } @Test fun `formatMealsToRows formats meal fields accurately and sorts chronologically descending`() { - val cal1 = Calendar.getInstance().apply { - set(2026, Calendar.MARCH, 15, 12, 30, 0) - set(Calendar.MILLISECOND, 0) - } - val cal2 = Calendar.getInstance().apply { - set(2026, Calendar.MARCH, 15, 20, 0, 0) - set(Calendar.MILLISECOND, 0) - } + val time1 = LocalDateTime.of(2026, 3, 15, 12, 30, 0) + .atZone(testZoneId) + .toInstant() + .toEpochMilli() + val time2 = LocalDateTime.of(2026, 3, 15, 20, 0, 0) + .atZone(testZoneId) + .toInstant() + .toEpochMilli() val meal1 = MealEntry( id = "meal-1", mealType = MealType.LUNCH.name, - mealTimestamp = cal1.timeInMillis, + mealTimestamp = time1, hungerBefore = 3, satietyAfter = 7, note = "Repas calme et savoureux", @@ -41,24 +44,24 @@ class GoogleSheetsDataFormatterTest { MealFoodItem("Riz complet", 150.0, FoodUnit.G).serialize(), MealFoodItem("Saumon", 120.0, FoodUnit.G).serialize() ), - photosBase64 = listOf("photo1") + photoUris = listOf("file:///photo1.jpg") ) val meal2 = MealEntry( id = "meal-2", mealType = MealType.DINNER.name, - mealTimestamp = cal2.timeInMillis, + mealTimestamp = time2, hungerBefore = 4, satietyAfter = 8, note = "Dîner léger en famille", foodItemsSerialized = listOf( MealFoodItem("Soupe de légumes", 250.0, FoodUnit.ML).serialize() ), - photosBase64 = emptyList() + photoUris = emptyList() ) // Pass in reverse order to test sorting - val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2)) + val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2), testZoneId) // 1 header + 2 data rows assertEquals(3, rows.size) diff --git a/app/src/test/java/com/example/LocalDatabaseTest.kt b/app/src/test/java/com/example/LocalDatabaseTest.kt index 3237027..34d67cd 100644 --- a/app/src/test/java/com/example/LocalDatabaseTest.kt +++ b/app/src/test/java/com/example/LocalDatabaseTest.kt @@ -12,7 +12,7 @@ import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -45,7 +45,7 @@ class LocalDatabaseTest { } @Test - fun testInsertAndObserveMeal() = runBlocking { + fun testInsertAndObserveMeal() = runTest { val meal = MealEntry( id = "local_test_1", mealType = MealType.LUNCH.name, @@ -55,9 +55,9 @@ class LocalDatabaseTest { note = "Repas calme", foodItemsSerialized = listOf( MealFoodItem("Riz", 150.0, FoodUnit.G).serialize() - ) + ), + photoUris = listOf("file:///test_photo.jpg") ) - val entity = LocalMealEntity.fromMealEntry(meal) dao.insertMeal(entity) @@ -71,10 +71,11 @@ class LocalDatabaseTest { assertEquals("Repas calme", readMeal.note) assertEquals(1, readMeal.parsedFoodItems().size) assertEquals("Riz", readMeal.parsedFoodItems()[0].name) + assertEquals(1, readMeal.displayPhotoUris.size) } @Test - fun testDeleteMeal() = runBlocking { + fun testDeleteMeal() = runTest { val entity = LocalMealEntity( id = "to_delete", mealType = MealType.DINNER.name, @@ -90,7 +91,7 @@ class LocalDatabaseTest { } @Test - fun testInsertAndObserveCustomFoods() = runBlocking { + fun testInsertAndObserveCustomFoods() = runTest { val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G) val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML) diff --git a/app/src/test/java/com/example/MealWeeklyStatsTest.kt b/app/src/test/java/com/example/MealWeeklyStatsTest.kt new file mode 100644 index 0000000..85e4d84 --- /dev/null +++ b/app/src/test/java/com/example/MealWeeklyStatsTest.kt @@ -0,0 +1,48 @@ +package com.example + +import com.example.data.model.MealEntry +import com.example.data.model.MealType +import com.example.domain.WeeklyStatsCalculator +import org.junit.Assert.assertEquals +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId + +class MealWeeklyStatsTest { + + private val testZoneId = ZoneId.of("Europe/Paris") + + @Test + fun `computeWeeklyStats returns 7 daily slots and correct distribution`() { + val today = LocalDate.now(testZoneId) + val todayMillis = today.atTime(12, 30).atZone(testZoneId).toInstant().toEpochMilli() + val twoDaysAgoMillis = today.minusDays(2).atTime(20, 0).atZone(testZoneId).toInstant().toEpochMilli() + + val meals = listOf( + MealEntry( + id = "m1", + mealType = MealType.LUNCH.name, + mealTimestamp = todayMillis, + hungerBefore = 5, + satietyAfter = 7 + ), + MealEntry( + id = "m2", + mealType = MealType.DINNER.name, + mealTimestamp = twoDaysAgoMillis, + hungerBefore = 3, + satietyAfter = 6 + ) + ) + + val stats = WeeklyStatsCalculator.computeWeeklyStats(meals, testZoneId) + + assertEquals(7, stats.dailyStats.size) + assertEquals(2, stats.totalMealsLast7Days) + assertEquals(6.5f, stats.averageSatiety, 0.01f) + assertEquals(4.0f, stats.averageHunger, 0.01f) + assertEquals(100, stats.optimalZonePercentage) // Both 7 and 6 are in 6..8 + assertEquals(1, stats.mealTypeDistribution[MealType.LUNCH]) + assertEquals(1, stats.mealTypeDistribution[MealType.DINNER]) + } +} diff --git a/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt b/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt index d588b6d..a5f224e 100644 --- a/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt +++ b/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt @@ -22,7 +22,7 @@ import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode @RunWith(RobolectricTestRunner::class) -@Config(manifest = Config.NONE) +@Config(manifest = Config.NONE, sdk = [34]) @LooperMode(LooperMode.Mode.INSTRUMENTATION_TEST) abstract class FirestoreEmulatorTestBase { @@ -37,7 +37,7 @@ abstract class FirestoreEmulatorTestBase { databaseId = if (resId != 0) context.getString(resId) else "demo-database" val app = if (FirebaseApp.getApps(context).isEmpty()) { - val newApp = FirebaseApp.initializeApp( + FirebaseApp.initializeApp( context, FirebaseOptions.Builder() .setApplicationId("com.example.app") @@ -45,21 +45,22 @@ abstract class FirestoreEmulatorTestBase { .setApiKey("fake-api-key-for-emulator") .build() ) - val newFirestore = FirebaseFirestore.getInstance(newApp, databaseId) - newFirestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT) - newFirestore.firestoreSettings = FirebaseFirestoreSettings.Builder() - .setLocalCacheSettings(MemoryCacheSettings.newBuilder().build()) - .build() - - val newAuth = FirebaseAuth.getInstance(newApp) - newAuth.useEmulator(EMULATOR_HOST, AUTH_PORT) - newApp } else { FirebaseApp.getInstance() } firestore = FirebaseFirestore.getInstance(app, databaseId) + try { + firestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT) + firestore.firestoreSettings = FirebaseFirestoreSettings.Builder() + .setLocalCacheSettings(MemoryCacheSettings.newBuilder().build()) + .build() + } catch (_: IllegalStateException) {} + auth = FirebaseAuth.getInstance(app) + try { + auth.useEmulator(EMULATOR_HOST, AUTH_PORT) + } catch (_: IllegalStateException) {} } @After diff --git a/firestore.rules b/firestore.rules index 2d3b386..eb028cc 100644 --- a/firestore.rules +++ b/firestore.rules @@ -36,6 +36,7 @@ service cloud.firestore { data.satietyAfter is int && data.satietyAfter >= 1 && data.satietyAfter <= 10 && (!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 1000)) && (!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || data.foodItemsSerialized[0] is string))) && + (!('photoUris' in data) || data.photoUris == null || (data.photoUris is list && data.photoUris.size() <= 6 && (data.photoUris.size() == 0 || data.photoUris[0] is string))) && (!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 6 && (data.photosBase64.size() == 0 || data.photosBase64[0] is string))) && (!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time)); } @@ -57,7 +58,7 @@ service cloud.firestore { allow create: if isOwner(userId) && isValidId(mealId) && incoming().keys().hasAll(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'createdAt']) && - incoming().keys().hasOnly(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'createdAt', 'updatedAt']) && + incoming().keys().hasOnly(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photoUris', 'photosBase64', 'createdAt', 'updatedAt']) && incoming().createdAt is timestamp && incoming().createdAt <= request.time && isValidMealEntry(incoming()); @@ -67,7 +68,7 @@ service cloud.firestore { incoming().userId == existing().userId && incoming().createdAt == existing().createdAt && isValidMealEntry(incoming()) && - incoming().diff(existing()).affectedKeys().hasOnly(['mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'updatedAt']); + incoming().diff(existing()).affectedKeys().hasOnly(['mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photoUris', 'photosBase64', 'updatedAt']); allow delete: if isOwner(userId) && isValidId(mealId); } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..61285a6 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e509b2d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega