From 79eb9d43668702cf21dce2d5d109462e82e35a91 Mon Sep 17 00:00:00 2001 From: mudabbir-ahmad Date: Wed, 4 Mar 2026 17:45:56 +0000 Subject: [PATCH] Add calendar screen and enhance habit logging features: implement logs retrieval for date ranges, update UI components, and manage habit streaks --- .idea/misc.xml | 2 +- app/build.gradle.kts | 4 + .../com/example/madwellbeingapp/HabitApp.kt | 23 - .../example/madwellbeingapp/MainActivity.kt | 148 ++---- .../data/dao/ActivityTypeDao.kt | 3 - .../madwellbeingapp/data/dao/HabitDao.kt | 3 - .../madwellbeingapp/data/dao/HabitLogDao.kt | 3 + .../data/repository/HabitRepository.kt | 6 +- .../ui/screens/AddEditHabitScreen.kt | 457 ++++-------------- .../ui/screens/AllActivitiesScreen.kt | 45 +- .../ui/screens/CalendarScreen.kt | 327 +++++++++++++ .../ui/screens/HabitDetailScreen.kt | 208 ++++---- .../madwellbeingapp/ui/screens/HomeScreen.kt | 198 ++++---- .../ui/screens/LandingScreen.kt | 5 +- .../ui/screens/SharedComponents.kt | 91 ++-- .../ui/viewmodel/HabitViewModel.kt | 159 ++---- gradle/libs.versions.toml | 3 + gradlew | 0 18 files changed, 821 insertions(+), 864 deletions(-) create mode 100644 app/src/main/java/com/example/madwellbeingapp/ui/screens/CalendarScreen.kt mode change 100644 => 100755 gradlew diff --git a/.idea/misc.xml b/.idea/misc.xml index b2c751a..2b2f1af 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 64ab646..37f930a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -60,6 +60,10 @@ dependencies { // ViewModel Compose implementation(libs.androidx.lifecycle.viewmodel.compose) + // Navigation3 + implementation(libs.androidx.navigation3) + implementation(libs.androidx.navigation3.ui) + testImplementation(libs.junit) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) diff --git a/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt b/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt index 5b65b7e..0256ed5 100644 --- a/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt +++ b/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt @@ -1,9 +1,6 @@ package com.example.madwellbeingapp import android.app.Application -import android.app.NotificationChannel -import android.app.NotificationManager -import android.os.Build import com.example.madwellbeingapp.data.HabitDatabase import com.example.madwellbeingapp.data.repository.HabitRepository @@ -17,27 +14,7 @@ class HabitApp : Application() { HabitRepository(database.habitDao(), database.habitLogDao(), database.activityTypeDao()) } - override fun onCreate() { - super.onCreate() - createNotificationChannel() - } - - private fun createNotificationChannel() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val channel = NotificationChannel( - CHANNEL_ID, - "Habit Reminders", - NotificationManager.IMPORTANCE_DEFAULT - ).apply { - description = "Daily reminders for your habits" - } - val manager = getSystemService(NotificationManager::class.java) - manager.createNotificationChannel(channel) - } - } - companion object { const val CHANNEL_ID = "habit_reminders" } } - diff --git a/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt b/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt index a6d41d3..1f8407c 100644 --- a/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt +++ b/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt @@ -1,22 +1,21 @@ package com.example.madwellbeingapp -import android.Manifest -import android.content.pm.PackageManager -import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge -import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.ui.NavDisplay import com.example.madwellbeingapp.ui.screens.ActiveOnlyScreen import com.example.madwellbeingapp.ui.screens.AddEditHabitScreen import com.example.madwellbeingapp.ui.screens.AllActivitiesScreen +import com.example.madwellbeingapp.ui.screens.CalendarScreen import com.example.madwellbeingapp.ui.screens.HabitDetailScreen import com.example.madwellbeingapp.ui.screens.HomeScreen import com.example.madwellbeingapp.ui.screens.LandingScreen @@ -24,126 +23,67 @@ import com.example.madwellbeingapp.ui.theme.MadWellbeingAppTheme import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel class MainActivity : ComponentActivity() { - - private val notificationPermissionLauncher = - registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* granted or not */ } - override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() - - // Request notification permission on Android 13+ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) - != PackageManager.PERMISSION_GRANTED - ) { - notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) - } - } - - setContent { - MadWellbeingAppTheme { - HabitNavGraph() - } - } + setContent { MadWellbeingAppTheme { HabitNavGraph() } } } } -/** - * Simple sealed class representing each screen destination. - * We avoid using Navigation Compose library and use manual state-based navigation. - */ +// ── Screen destinations ───────────────────────────────────── sealed class Screen { - /** Landing page with 3 navigation buttons — first page the user sees. */ data object Landing : Screen() - /** All activities — past completed + currently active. */ data object AllActivities : Screen() - /** Manage activities — add new habits, swipe to complete. */ data object Home : Screen() - /** Active only — habits still to-do today. */ data object ActiveOnly : Screen() + data object Calendar : Screen() data object AddHabit : Screen() data class EditHabit(val habitId: Int) : Screen() data class HabitDetail(val habitId: Int) : Screen() } @Composable -fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) { - // Manual back-stack — starts on the Landing screen - val backStack = remember { mutableStateListOf(Screen.Landing) } - val currentScreen = backStack.last() +fun HabitNavGraph(vm: HabitViewModel = viewModel()) { + val backStack = remember { mutableStateListOf(Screen.Landing) } - fun navigateTo(screen: Screen) { - backStack.add(screen) - } + fun nav(screen: Screen) = backStack.add(screen) + fun back() { if (backStack.size > 1) backStack.removeLast() } - fun navigateBack() { - if (backStack.size > 1) { - backStack.removeAt(backStack.lastIndex) - } - } - - when (currentScreen) { - is Screen.Landing -> { - LandingScreen( - onAllActivities = { navigateTo(Screen.AllActivities) }, - onManageActivities = { navigateTo(Screen.Home) }, - onActiveOnly = { navigateTo(Screen.ActiveOnly) } - ) - } - - is Screen.AllActivities -> { - AllActivitiesScreen( - viewModel = viewModel, - onNavigateBack = { navigateBack() }, - onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) } - ) - } - - is Screen.Home -> { - HomeScreen( - viewModel = viewModel, - onAddHabit = { navigateTo(Screen.AddHabit) }, - onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) }, - onNavigateBack = { navigateBack() } - ) - } - - is Screen.ActiveOnly -> { - ActiveOnlyScreen( - viewModel = viewModel, - onNavigateBack = { navigateBack() }, - onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) } - ) - } - - is Screen.AddHabit -> { - AddEditHabitScreen( - viewModel = viewModel, - existingHabit = null, - onNavigateBack = { navigateBack() } - ) - } - - is Screen.EditHabit -> { - val allHabits by viewModel.allHabits.collectAsState() - val habit = allHabits.find { it.id == currentScreen.habitId } - if (habit != null) { - AddEditHabitScreen( - viewModel = viewModel, - existingHabit = habit, - onNavigateBack = { navigateBack() } + NavDisplay( + backStack = backStack, + entryProvider = entryProvider { + entry { + LandingScreen( + onAllActivities = { nav(Screen.AllActivities) }, + onManageActivities = { nav(Screen.Home) }, + onActiveOnly = { nav(Screen.ActiveOnly) }, + onCalendar = { nav(Screen.Calendar) } ) } + entry { + AllActivitiesScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) }) + } + entry { + HomeScreen(vm, onAddHabit = { nav(Screen.AddHabit) }, onHabitClick = { nav(Screen.HabitDetail(it)) }, onNavigateBack = ::back) + } + entry { + ActiveOnlyScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) }) + } + entry { + CalendarScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) }) + } + entry { + AddEditHabitScreen(vm, existingHabit = null, onNavigateBack = ::back) + } + entry { key -> + val allHabits by vm.allHabits.collectAsState() + allHabits.find { it.id == key.habitId }?.let { habit -> + AddEditHabitScreen(vm, existingHabit = habit, onNavigateBack = ::back) + } + } + entry { key -> + HabitDetailScreen(key.habitId, vm, onNavigateBack = ::back, onEditHabit = { nav(Screen.EditHabit(it)) }) + } } - - is Screen.HabitDetail -> { - HabitDetailScreen( - habitId = currentScreen.habitId, - viewModel = viewModel, - onNavigateBack = { navigateBack() }, - onEditHabit = { id -> navigateTo(Screen.EditHabit(id)) } - ) - } - } + ) } \ No newline at end of file diff --git a/app/src/main/java/com/example/madwellbeingapp/data/dao/ActivityTypeDao.kt b/app/src/main/java/com/example/madwellbeingapp/data/dao/ActivityTypeDao.kt index c108453..d8bef52 100644 --- a/app/src/main/java/com/example/madwellbeingapp/data/dao/ActivityTypeDao.kt +++ b/app/src/main/java/com/example/madwellbeingapp/data/dao/ActivityTypeDao.kt @@ -1,7 +1,6 @@ package com.example.madwellbeingapp.data.dao import androidx.room.Dao -import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import com.example.madwellbeingapp.data.model.ActivityType @@ -13,8 +12,6 @@ interface ActivityTypeDao { @Upsert suspend fun upsert(activityType: ActivityType): Long - @Delete - suspend fun delete(activityType: ActivityType): Int @Query("SELECT * FROM activity_types ORDER BY name ASC") fun getAll(): Flow> diff --git a/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitDao.kt b/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitDao.kt index 05a2bf7..b78e2eb 100644 --- a/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitDao.kt +++ b/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitDao.kt @@ -1,7 +1,6 @@ package com.example.madwellbeingapp.data.dao import androidx.room.Dao -import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import com.example.madwellbeingapp.data.model.Habit @@ -13,8 +12,6 @@ interface HabitDao { @Upsert suspend fun upsert(habit: Habit): Long - @Delete - suspend fun delete(habit: Habit): Int @Query("SELECT * FROM habits ORDER BY name ASC") fun getAllHabits(): Flow> diff --git a/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitLogDao.kt b/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitLogDao.kt index 908140f..db67bd9 100644 --- a/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitLogDao.kt +++ b/app/src/main/java/com/example/madwellbeingapp/data/dao/HabitLogDao.kt @@ -29,4 +29,7 @@ interface HabitLogDao { @Query("SELECT * FROM habit_logs WHERE date = :date") fun getLogsForDate(date: Long): Flow> + + @Query("SELECT * FROM habit_logs WHERE date >= :startDate AND date <= :endDate AND completed = 1") + fun getLogsBetween(startDate: Long, endDate: Long): Flow> } diff --git a/app/src/main/java/com/example/madwellbeingapp/data/repository/HabitRepository.kt b/app/src/main/java/com/example/madwellbeingapp/data/repository/HabitRepository.kt index 4ef4fb5..d19556f 100644 --- a/app/src/main/java/com/example/madwellbeingapp/data/repository/HabitRepository.kt +++ b/app/src/main/java/com/example/madwellbeingapp/data/repository/HabitRepository.kt @@ -28,7 +28,6 @@ class HabitRepository( suspend fun updateHabit(habit: Habit) = habitDao.upsert(habit) - suspend fun deleteHabit(habit: Habit) = habitDao.delete(habit) /** Returns an existing habit with the same name+details (case-insensitive), or null. */ suspend fun findDuplicate(name: String, details: String): Habit? = @@ -40,8 +39,6 @@ class HabitRepository( suspend fun addActivityType(activityType: ActivityType): Long = activityTypeDao.upsert(activityType) - suspend fun deleteActivityType(activityType: ActivityType) = - activityTypeDao.delete(activityType) suspend fun findActivityTypeByName(name: String): ActivityType? = activityTypeDao.findByName(name) @@ -70,4 +67,7 @@ class HabitRepository( suspend fun getCompletedLogsDesc(habitId: Int): List = habitLogDao.getCompletedLogsDesc(habitId) + + fun getLogsBetween(startDate: Long, endDate: Long): Flow> = + habitLogDao.getLogsBetween(startDate, endDate) } diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/AddEditHabitScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/AddEditHabitScreen.kt index b040ceb..6ade69c 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/AddEditHabitScreen.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/AddEditHabitScreen.kt @@ -1,12 +1,7 @@ package com.example.madwellbeingapp.ui.screens -import android.util.Log import android.widget.Toast -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectDragGestures 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 @@ -18,13 +13,10 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn 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.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme @@ -35,42 +27,20 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -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.geometry.Offset -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity 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.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel -import kotlin.math.PI -import kotlin.math.atan2 -import kotlin.math.cos -import kotlin.math.roundToInt -import kotlin.math.sin /** * Screen for creating or editing a habit. - * - * - Activity type is chosen from a dropdown populated by user-created types stored in Room. - * - A "+" button lets the user add new activity types on the fly. - * - Details field lets the user specialise the activity (e.g. "Legs"). - * - Reminder time uses a clock-style dial picker instead of typing. - * - All text is title-cased. Duplicates are blocked. - * - rememberSaveable preserves state across rotation. */ @Composable fun AddEditHabitScreen( @@ -80,68 +50,57 @@ fun AddEditHabitScreen( ) { val context = LocalContext.current val isEditing = existingHabit != null - - // Activity types from the database val activityTypes by viewModel.allActivityTypes.collectAsState() - // ── Form state (survives rotation) ────────────────────── - var selectedActivityName by rememberSaveable { mutableStateOf(existingHabit?.name ?: "") } - var details by rememberSaveable { mutableStateOf(existingHabit?.details ?: "") } - var targetFrequency by rememberSaveable { - mutableStateOf((existingHabit?.targetFrequency ?: 7).toString()) - } - var reminderEnabled by rememberSaveable { mutableStateOf(existingHabit?.reminderEnabled ?: true) } - var reminderHour by rememberSaveable { mutableIntStateOf(existingHabit?.reminderHour ?: 9) } - var reminderMinute by rememberSaveable { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) } + // Form state + var selectedActivityName by remember { mutableStateOf(existingHabit?.name ?: "") } + var details by remember { mutableStateOf(existingHabit?.details ?: "") } + var targetFrequency by remember { mutableStateOf((existingHabit?.targetFrequency ?: 7).toString()) } + var reminderEnabled by remember { mutableStateOf(existingHabit?.reminderEnabled ?: true) } + var reminderHour by remember { mutableStateOf(existingHabit?.reminderHour ?: 9) } + var reminderMinute by remember { mutableStateOf(existingHabit?.reminderMinute ?: 0) } - var nameError by rememberSaveable { mutableStateOf(false) } - var showActivityDialog by rememberSaveable { mutableStateOf(false) } - var showAddTypeDialog by rememberSaveable { mutableStateOf(false) } - var showTimePicker by rememberSaveable { mutableStateOf(false) } + var nameError by remember { mutableStateOf(false) } + var showActivityDialog by remember { mutableStateOf(false) } + var showAddTypeDialog by remember { mutableStateOf(false) } + var showTimePicker by remember { mutableStateOf(false) } - // ── Activity type picker dialog ───────────────────────── + // Activity type picker dialog if (showActivityDialog) { AlertDialog( onDismissRequest = { showActivityDialog = false }, title = { Text("Select Activity Type") }, text = { if (activityTypes.isEmpty()) { - Text( - "No activity types yet.\nTap the + button to create one.", + Text("No activity types yet.\nTap the + button to create one.", style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) + color = MaterialTheme.colorScheme.onSurfaceVariant) } else { LazyColumn { items(activityTypes) { type -> - Text( - text = type.name, - modifier = Modifier - .fillMaxWidth() - .clickable { - selectedActivityName = type.name - nameError = false - showActivityDialog = false - } - .padding(vertical = 12.dp, horizontal = 8.dp), - style = MaterialTheme.typography.bodyLarge, - fontWeight = if (type.name == selectedActivityName) - FontWeight.Bold else FontWeight.Normal, - color = if (type.name == selectedActivityName) - MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.onSurface - ) + TextButton(onClick = { + selectedActivityName = type.name + nameError = false + showActivityDialog = false + }, modifier = Modifier.fillMaxWidth()) { + Text( + text = type.name, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (type.name == selectedActivityName) FontWeight.Bold + else FontWeight.Normal, + color = if (type.name == selectedActivityName) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface + ) + } } } } }, - confirmButton = { - TextButton(onClick = { showActivityDialog = false }) { Text("Close") } - } + confirmButton = { TextButton(onClick = { showActivityDialog = false }) { Text("Close") } } ) } - // ── Add new activity type dialog ──────────────────────── + // Add new activity type dialog if (showAddTypeDialog) { var newTypeName by remember { mutableStateOf("") } var typeError by remember { mutableStateOf(false) } @@ -157,15 +116,12 @@ fun AddEditHabitScreen( placeholder = { Text("e.g. Gym, Running, Yoga") }, singleLine = true, isError = typeError, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(12.dp) + modifier = Modifier.fillMaxWidth() ) if (typeError) { - Text( - "Name is empty or already exists", + Text("Name is empty or already exists", style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) + color = MaterialTheme.colorScheme.error) } } }, @@ -186,135 +142,85 @@ fun AddEditHabitScreen( } }) { Text("Add") } }, - dismissButton = { - TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") } - } + dismissButton = { TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") } } ) } - // ── Time picker dialog (clock dial) ───────────────────── + // Time picker dialog (simple number-based instead of clock dial) if (showTimePicker) { - var tempHour by remember { mutableIntStateOf(reminderHour) } - var tempMinute by remember { mutableIntStateOf(reminderMinute) } - var pickingHour by remember { mutableStateOf(true) } - + var tempHour by remember { mutableStateOf(reminderHour.toString()) } + var tempMinute by remember { mutableStateOf(reminderMinute.toString()) } AlertDialog( onDismissRequest = { showTimePicker = false }, - title = { - Text( - if (pickingHour) "Select Hour" else "Select Minute", - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() - ) - }, + title = { Text("Set Reminder Time") }, text = { - Column( - horizontalAlignment = Alignment.CenterHorizontally, + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { - // Display current selection - Text( - text = "${tempHour.toString().padStart(2, '0')}:${tempMinute.toString().padStart(2, '0')}", - style = MaterialTheme.typography.headlineLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() + OutlinedTextField( + value = tempHour, + onValueChange = { tempHour = it.filter { c -> c.isDigit() }.take(2) }, + label = { Text("Hour") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + singleLine = true, + modifier = Modifier.weight(1f) ) - Spacer(modifier = Modifier.height(4.dp)) - // Toggle hour/minute - Row( - horizontalArrangement = Arrangement.Center, - modifier = Modifier.fillMaxWidth() - ) { - TextButton(onClick = { pickingHour = true }) { - Text( - "Hour", - fontWeight = if (pickingHour) FontWeight.Bold else FontWeight.Normal, - color = if (pickingHour) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.onSurfaceVariant - ) - } - TextButton(onClick = { pickingHour = false }) { - Text( - "Minute", - fontWeight = if (!pickingHour) FontWeight.Bold else FontWeight.Normal, - color = if (!pickingHour) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - Spacer(modifier = Modifier.height(8.dp)) - // Clock dial - ClockDial( - value = if (pickingHour) tempHour else tempMinute, - maxValue = if (pickingHour) 24 else 60, - step = if (pickingHour) 1 else 5, - onValueChange = { - if (pickingHour) tempHour = it else tempMinute = it - }, - labels = if (pickingHour) (0..23 step 3).toList() - else (0..55 step 5).toList() + Text(":", style = MaterialTheme.typography.headlineMedium, + fontWeight = FontWeight.Bold) + OutlinedTextField( + value = tempMinute, + onValueChange = { tempMinute = it.filter { c -> c.isDigit() }.take(2) }, + label = { Text("Min") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + singleLine = true, + modifier = Modifier.weight(1f) ) } }, confirmButton = { TextButton(onClick = { - reminderHour = tempHour - reminderMinute = tempMinute + reminderHour = (tempHour.toIntOrNull() ?: 9).coerceIn(0, 23) + reminderMinute = (tempMinute.toIntOrNull() ?: 0).coerceIn(0, 59) showTimePicker = false }) { Text("OK") } }, - dismissButton = { - TextButton(onClick = { showTimePicker = false }) { Text("Cancel") } - } + dismissButton = { TextButton(onClick = { showTimePicker = false }) { Text("Cancel") } } ) } - // ── Screen layout ─────────────────────────────────────── + // Screen layout Scaffold { padding -> - Column( - modifier = Modifier - .fillMaxSize() - .padding(padding) - ) { + Column(modifier = Modifier.fillMaxSize().padding(padding)) { ScreenHeader( title = if (isEditing) "Edit Habit" else "New Habit", onBack = onNavigateBack ) Column( - modifier = Modifier - .fillMaxSize() - .padding(20.dp) + modifier = Modifier.fillMaxSize().padding(20.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp) ) { - // ── Activity type dropdown + add button ───────── - Text( - text = "Activity Type", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) + // Activity type dropdown + add button + Text("Activity Type", style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { Card( - modifier = Modifier - .weight(1f) - .clickable { showActivityDialog = true }, - shape = RoundedCornerShape(12.dp), + onClick = { showActivityDialog = true }, + modifier = Modifier.weight(1f), elevation = CardDefaults.cardElevation(1.dp), colors = if (nameError) CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer - ) else CardDefaults.cardColors() + containerColor = MaterialTheme.colorScheme.errorContainer) + else CardDefaults.cardColors() ) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { @@ -326,41 +232,34 @@ fun AddEditHabitScreen( MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) else MaterialTheme.colorScheme.onSurface ) - Text( - text = "▼", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) + Text("▼", style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) } } - // "+" button to add a new activity type Button( onClick = { showAddTypeDialog = true }, modifier = Modifier.size(52.dp), - shape = RoundedCornerShape(12.dp), contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp) ) { - Text("+", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Text("+", style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold) } } if (nameError) { - Text( - text = "Please select an activity type", + Text("Please select an activity type", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(start = 4.dp) - ) + modifier = Modifier.padding(start = 4.dp)) } - // ── Details text field ────────────────────────── + // Details OutlinedTextField( value = details, onValueChange = { details = it }, label = { Text("Details (optional)") }, placeholder = { Text("e.g. Legs, Upper Body, 5K") }, singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(12.dp) + modifier = Modifier.fillMaxWidth() ) // Live preview @@ -370,65 +269,48 @@ fun AddEditHabitScreen( else HabitViewModel.toTitleCase(selectedActivityName.trim()) + "(" + HabitViewModel.toTitleCase(details.trim()) + ")" - Text( - text = "Will display as: $previewName", + Text("Will display as: $previewName", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding(start = 4.dp) - ) + modifier = Modifier.padding(start = 4.dp)) } - // ── Target frequency ──────────────────────────── + // Target frequency OutlinedTextField( value = targetFrequency, onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } }, label = { Text("Target (times per week)") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), singleLine = true, - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(12.dp) + modifier = Modifier.fillMaxWidth() ) - // ── Reminder toggle ───────────────────────────── + // Reminder toggle Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text("Daily Reminder", style = MaterialTheme.typography.bodyLarge) - Button( - onClick = { reminderEnabled = !reminderEnabled }, - colors = if (reminderEnabled) ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.primary - ) else ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - contentColor = MaterialTheme.colorScheme.onSurfaceVariant - ), - shape = RoundedCornerShape(8.dp) - ) { + Button(onClick = { reminderEnabled = !reminderEnabled }) { Text(if (reminderEnabled) "ON" else "OFF") } } if (reminderEnabled) { - // ── Reminder time — clock dial button ─────── Card( - modifier = Modifier - .fillMaxWidth() - .clickable { showTimePicker = true }, - shape = RoundedCornerShape(12.dp), + onClick = { showTimePicker = true }, + modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(1.dp) ) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text("Reminder Time", style = MaterialTheme.typography.bodyLarge) Text( - text = "${reminderHour.toString().padStart(2, '0')}:${reminderMinute.toString().padStart(2, '0')}", + "${reminderHour.toString().padStart(2, '0')}:${reminderMinute.toString().padStart(2, '0')}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary @@ -439,18 +321,15 @@ fun AddEditHabitScreen( Spacer(modifier = Modifier.height(8.dp)) - // ── Save button ───────────────────────────────── + // Save button Button( onClick = { - if (selectedActivityName.isBlank()) { - nameError = true - return@Button - } + if (selectedActivityName.isBlank()) { nameError = true; return@Button } val freq = targetFrequency.toIntOrNull() ?: 7 - if (isEditing && existingHabit != null) { + if (isEditing) { viewModel.updateHabit( - existingHabit.copy( + existingHabit!!.copy( name = selectedActivityName.trim(), details = details.trim(), activityType = selectedActivityName.trim(), @@ -460,7 +339,6 @@ fun AddEditHabitScreen( reminderMinute = reminderMinute ) ) - Log.i("AddEditHabitScreen", "User updated habit: name='${selectedActivityName.trim()}'") onNavigateBack() } else { viewModel.addHabit( @@ -472,20 +350,13 @@ fun AddEditHabitScreen( reminderHour = reminderHour, reminderMinute = reminderMinute, onResult = { success -> - if (success) { - Log.i("AddEditHabitScreen", "User created habit: name='${selectedActivityName.trim()}'") - onNavigateBack() - } else { - Toast.makeText(context, "This activity already exists!", Toast.LENGTH_SHORT).show() - } + if (success) onNavigateBack() + else Toast.makeText(context, "This activity already exists!", Toast.LENGTH_SHORT).show() } ) } }, - modifier = Modifier - .fillMaxWidth() - .height(52.dp), - shape = RoundedCornerShape(14.dp) + modifier = Modifier.fillMaxWidth().height(52.dp) ) { Text( if (isEditing) "Update Habit" else "Create Habit", @@ -497,139 +368,3 @@ fun AddEditHabitScreen( } } } - -// ───────────────────────────────────────────────────────────── -// Clock-style dial picker — pure Compose Canvas, no 3rd-party -// ───────────────────────────────────────────────────────────── - -/** - * A circular dial the user drags to pick a value. - * [value] is the current selection, [maxValue] is the range (24 for hours, 60 for minutes). - * [step] snaps to multiples (1 for hours, 5 for minutes). - * [labels] are the numbers drawn around the ring. - */ -@Composable -private fun ClockDial( - value: Int, - maxValue: Int, - step: Int, - onValueChange: (Int) -> Unit, - labels: List -) { - val sizeDp = 220.dp - val sizePx = with(LocalDensity.current) { sizeDp.toPx() } - val center = sizePx / 2f - val radius = center * 0.82f - val labelRadius = center * 0.68f - val knobRadius = 18f - - val primaryColor = MaterialTheme.colorScheme.primary - val surfaceVariantColor = MaterialTheme.colorScheme.surfaceVariant - val onSurfaceColor = MaterialTheme.colorScheme.onSurface - val onPrimaryColor = MaterialTheme.colorScheme.onPrimary - - // Convert current value to angle (0 at top = -PI/2) - fun valueToAngle(v: Int): Float { - return (2f * PI.toFloat() * v / maxValue) - (PI.toFloat() / 2f) - } - - var currentAngle by remember(value) { mutableFloatStateOf(valueToAngle(value)) } - - Box( - modifier = Modifier - .size(sizeDp) - .pointerInput(maxValue, step) { - detectDragGestures { change, _ -> - change.consume() - val pos = change.position - val angle = atan2(pos.y - center, pos.x - center) - currentAngle = angle - - // Convert angle back to value - var normalized = angle + (PI.toFloat() / 2f) - if (normalized < 0) normalized += 2f * PI.toFloat() - var raw = (normalized / (2f * PI.toFloat()) * maxValue).roundToInt() - // Snap to step - raw = ((raw.toFloat() / step).roundToInt() * step).coerceIn(0, maxValue - 1) - onValueChange(raw) - } - } - ) { - androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) { - // Outer ring - drawCircle( - color = surfaceVariantColor, - radius = radius, - center = Offset(center, center), - style = Stroke(width = 4f) - ) - - // Draw labels around the circle - for (lbl in labels) { - val a = valueToAngle(lbl) - val lx = center + labelRadius * cos(a) - val ly = center + labelRadius * sin(a) - drawCircle( - color = if (lbl == value) primaryColor else Color.Transparent, - radius = 16f, - center = Offset(lx, ly) - ) - } - - // Line from center to knob - val knobAngle = valueToAngle(value) - val kx = center + radius * cos(knobAngle) - val ky = center + radius * sin(knobAngle) - drawLine( - color = primaryColor, - start = Offset(center, center), - end = Offset(kx, ky), - strokeWidth = 3f - ) - - // Knob - drawCircle(color = primaryColor, radius = knobRadius, center = Offset(kx, ky)) - - // Center dot - drawCircle(color = primaryColor, radius = 6f, center = Offset(center, center)) - } - - // Draw text labels on top of canvas using Compose Text - labels.forEach { lbl -> - val a = valueToAngle(lbl) - val lx = center + labelRadius * cos(a) - val ly = center + labelRadius * sin(a) - val offsetXDp = with(LocalDensity.current) { lx.toDp() } - val offsetYDp = with(LocalDensity.current) { ly.toDp() } - Text( - text = lbl.toString().padStart(2, '0'), - modifier = Modifier - .size(32.dp) - .padding(start = (offsetXDp - 16.dp).coerceAtLeast(0.dp)) - .padding(top = (offsetYDp - 8.dp).coerceAtLeast(0.dp)), - style = MaterialTheme.typography.labelSmall, - fontWeight = if (lbl == value) FontWeight.Bold else FontWeight.Normal, - color = if (lbl == value) onPrimaryColor else onSurfaceColor, - textAlign = TextAlign.Center - ) - } - - // Big selected value in the center - Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Box( - modifier = Modifier - .size(52.dp) - .clip(CircleShape) - .background(MaterialTheme.colorScheme.primaryContainer), - contentAlignment = Alignment.Center - ) { - Text( - text = value.toString().padStart(2, '0'), - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onPrimaryContainer - ) - } - } - } -} diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/AllActivitiesScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/AllActivitiesScreen.kt index 68f5087..ac95b76 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/AllActivitiesScreen.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/AllActivitiesScreen.kt @@ -5,8 +5,10 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -15,6 +17,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel @@ -34,14 +37,16 @@ fun AllActivitiesScreen( ScreenHeader(title = "All Activities", onBack = onNavigateBack) if (habits.isEmpty()) { - Box(modifier = Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) { + Box(modifier = Modifier.fillMaxSize().padding(32.dp), + contentAlignment = Alignment.Center) { Text("No activities yet. Go to Manage Activities to create one!", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) } } else { LazyColumn( - modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 12.dp), + modifier = Modifier.fillMaxSize() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp) ) { items(habits, key = { it.id }) { habit -> @@ -52,12 +57,39 @@ fun AllActivitiesScreen( onClick = { onHabitClick(habit.id) }, circleColor = cardCircleColor(habit, done), circleText = cardCircleText(habit, done), - circleTextColor = if (done) MaterialTheme.colorScheme.onPrimary - else MaterialTheme.colorScheme.onSurfaceVariant, + circleTextColor = if (!habit.isActive) + MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + else if (done) MaterialTheme.colorScheme.onPrimary + else MaterialTheme.colorScheme.onSurfaceVariant, containerColor = cardContainerColor(habit, done), + contentAlpha = if (!habit.isActive) 0.5f else 1f, badge = if (!habit.isActive) { - { Text("Retired", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.error) } - } else null + { Text("Disabled", style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error) } + } else null, + trailing = if (!habit.isActive) { + { + Button( + onClick = { viewModel.enableHabit(habit) }, + modifier = Modifier.size(32.dp), + contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp) + ) { + Text("+", fontWeight = FontWeight.Bold, + style = MaterialTheme.typography.titleMedium) + } + } + } else { + { + Button( + onClick = { viewModel.disableHabit(habit) }, + modifier = Modifier.size(32.dp), + contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp) + ) { + Text("−", fontWeight = FontWeight.Bold, + style = MaterialTheme.typography.titleMedium) + } + } + } ) } } @@ -66,7 +98,6 @@ fun AllActivitiesScreen( } } -/** Resolves the circle background colour for a habit card. */ @Composable private fun cardCircleColor(habit: Habit, completedToday: Boolean) = when { !habit.isActive -> MaterialTheme.colorScheme.outline.copy(alpha = 0.4f) diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/CalendarScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/CalendarScreen.kt new file mode 100644 index 0000000..3c7cdd8 --- /dev/null +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/CalendarScreen.kt @@ -0,0 +1,327 @@ +package com.example.madwellbeingapp.ui.screens + +import androidx.compose.foundation.background +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.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.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.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.madwellbeingapp.data.model.Habit +import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Locale + +@Composable +fun CalendarScreen( + viewModel: HabitViewModel, + onNavigateBack: () -> Unit, + onHabitClick: (Int) -> Unit +) { + val habits by viewModel.allHabits.collectAsState() + val activeHabits = habits.filter { it.isActive } + + // Current displayed month + var displayYear by remember { mutableStateOf(Calendar.getInstance().get(Calendar.YEAR)) } + var displayMonth by remember { mutableStateOf(Calendar.getInstance().get(Calendar.MONTH)) } + + // Compute start/end of displayed month + val monthStart = remember(displayYear, displayMonth) { + val cal = Calendar.getInstance() + cal.set(displayYear, displayMonth, 1, 0, 0, 0) + cal.set(Calendar.MILLISECOND, 0) + cal.timeInMillis + } + val monthEnd = remember(displayYear, displayMonth) { + val cal = Calendar.getInstance() + cal.set(displayYear, displayMonth, 1, 0, 0, 0) + cal.set(Calendar.MILLISECOND, 0) + cal.add(Calendar.MONTH, 1) + cal.add(Calendar.MILLISECOND, -1) + cal.timeInMillis + } + + // Logs for displayed month + val monthLogs by viewModel.getLogsBetween(monthStart, monthEnd).collectAsState(initial = emptyList()) + + // Compute which days have completions and how many habits were completed + val dayCompletionMap = remember(monthLogs) { + val map = mutableMapOf>() // dayMillis -> set of habitIds + for (log in monthLogs) { + val dayMillis = normaliseDay(log.date) + map.getOrPut(dayMillis) { mutableSetOf() }.add(log.habitId) + } + map + } + + // Streaks for active habits + val streakMap = remember { mutableMapOf() } + LaunchedEffect(activeHabits) { + for (habit in activeHabits) { + if (!streakMap.containsKey(habit.id)) { + streakMap[habit.id] = viewModel.computeStreakForHabit(habit.id) + } + } + } + + // Calendar grid data + val daysInMonth = remember(displayYear, displayMonth) { + val cal = Calendar.getInstance() + cal.set(displayYear, displayMonth, 1) + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + } + val firstDayOfWeek = remember(displayYear, displayMonth) { + val cal = Calendar.getInstance() + cal.set(displayYear, displayMonth, 1) + // Monday=0, Sunday=6 + (cal.get(Calendar.DAY_OF_WEEK) + 5) % 7 + } + val monthLabel = remember(displayYear, displayMonth) { + val cal = Calendar.getInstance() + cal.set(displayYear, displayMonth, 1) + SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(cal.time) + } + + // Total active habits count for day intensity + val totalActive = activeHabits.size + + Scaffold { padding -> + Column(modifier = Modifier.fillMaxSize().padding(padding)) { + ScreenHeader(title = "Calendar", onBack = onNavigateBack) + + LazyColumn( + modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + // Month navigation + item { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + TextButton(onClick = { + if (displayMonth == 0) { displayMonth = 11; displayYear-- } + else displayMonth-- + }) { + Text("◀", style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary) + } + Text(monthLabel, style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold) + TextButton(onClick = { + if (displayMonth == 11) { displayMonth = 0; displayYear++ } + else displayMonth++ + }) { + Text("▶", style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary) + } + } + } + + // Weekday headers + item { + Row(modifier = Modifier.fillMaxWidth()) { + listOf("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su").forEach { day -> + Text( + text = day, modifier = Modifier.weight(1f), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + // Calendar grid rows + val totalCells = firstDayOfWeek + daysInMonth + val rows = (totalCells + 6) / 7 + items(rows) { rowIndex -> + Row(modifier = Modifier.fillMaxWidth()) { + for (col in 0..6) { + val cellIndex = rowIndex * 7 + col + val dayNum = cellIndex - firstDayOfWeek + 1 + if (dayNum in 1..daysInMonth) { + val dayCal = Calendar.getInstance() + dayCal.set(displayYear, displayMonth, dayNum, 0, 0, 0) + dayCal.set(Calendar.MILLISECOND, 0) + val dayMillis = dayCal.timeInMillis + val count = dayCompletionMap[dayMillis]?.size ?: 0 + val today = isToday(dayMillis) + val intensity = if (totalActive > 0) (count.toFloat() / totalActive).coerceIn(0f, 1f) else 0f + + Box( + modifier = Modifier.weight(1f).aspectRatio(1f).padding(2.dp) + .background( + when { + today -> MaterialTheme.colorScheme.primaryContainer + count == 0 -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f) + intensity < 0.5f -> MaterialTheme.colorScheme.primary.copy(alpha = 0.3f) + intensity < 1f -> MaterialTheme.colorScheme.primary.copy(alpha = 0.6f) + else -> MaterialTheme.colorScheme.primary + }, + shape = androidx.compose.foundation.shape.RoundedCornerShape(6.dp) + ), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + dayNum.toString(), + style = MaterialTheme.typography.labelSmall, + fontWeight = if (today) FontWeight.Bold else FontWeight.Normal, + color = when { + intensity >= 1f -> MaterialTheme.colorScheme.onPrimary + today -> MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.onSurface + } + ) + if (count > 0) { + Text("$count", style = MaterialTheme.typography.labelSmall, + color = if (intensity >= 1f) MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.8f) + else MaterialTheme.colorScheme.primary) + } + } + } + } else { + // Empty cell + Box(modifier = Modifier.weight(1f).aspectRatio(1f)) + } + } + } + } + + // Legend + item { + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + Box(modifier = Modifier.size(12.dp).background( + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), + shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp))) + Text(" None ", style = MaterialTheme.typography.labelSmall) + Box(modifier = Modifier.size(12.dp).background( + MaterialTheme.colorScheme.primary.copy(alpha = 0.3f), + shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp))) + Text(" Some ", style = MaterialTheme.typography.labelSmall) + Box(modifier = Modifier.size(12.dp).background( + MaterialTheme.colorScheme.primary, + shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp))) + Text(" All", style = MaterialTheme.typography.labelSmall) + } + } + + // Streak section + item { + Spacer(modifier = Modifier.height(8.dp)) + Text("Habit Streaks", style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold) + } + + if (activeHabits.isEmpty()) { + item { + Text("No active habits yet.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(vertical = 8.dp)) + } + } else { + items(activeHabits, key = { it.id }) { habit -> + val streak = streakMap[habit.id] ?: 0 + StreakCard(habit = habit, streak = streak, onClick = { onHabitClick(habit.id) }) + } + } + + item { Spacer(modifier = Modifier.height(16.dp)) } + } + } + } +} + +@Composable +private fun StreakCard(habit: Habit, streak: Int, onClick: () -> Unit) { + Card( + onClick = onClick, + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(2.dp), + colors = CardDefaults.cardColors( + containerColor = if (streak > 0) MaterialTheme.colorScheme.primaryContainer + else MaterialTheme.colorScheme.surface + ) + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // Fire icon for active streak + Box( + modifier = Modifier.size(40.dp).background( + if (streak > 0) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.surfaceVariant, + shape = androidx.compose.foundation.shape.CircleShape + ), + contentAlignment = Alignment.Center + ) { + Text(if (streak > 0) "🔥" else "—", style = MaterialTheme.typography.titleMedium) + } + Spacer(modifier = Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text(habit.displayName, style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold) + Text(habit.activityType + " • ${habit.targetFrequency}x/week", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text("$streak", style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + color = if (streak > 0) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurfaceVariant) + Text(if (streak == 1) "day" else "days", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } +} + +private fun normaliseDay(millis: Long): Long { + val c = Calendar.getInstance(); c.timeInMillis = millis + c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0) + c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) + return c.timeInMillis +} + +private fun isToday(millis: Long): Boolean { + val todayCal = Calendar.getInstance() + todayCal.set(Calendar.HOUR_OF_DAY, 0); todayCal.set(Calendar.MINUTE, 0) + todayCal.set(Calendar.SECOND, 0); todayCal.set(Calendar.MILLISECOND, 0) + return millis == todayCal.timeInMillis +} diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/HabitDetailScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/HabitDetailScreen.kt index b08b916..f0739a8 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/HabitDetailScreen.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/HabitDetailScreen.kt @@ -1,9 +1,6 @@ package com.example.madwellbeingapp.ui.screens -import android.util.Log import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -12,20 +9,14 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.offset 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.verticalScroll import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults -import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -34,24 +25,18 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf 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.input.pointer.pointerInput import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale -import kotlin.math.roundToInt @Composable fun HabitDetailScreen( @@ -70,22 +55,23 @@ fun HabitDetailScreen( val todayLogs by viewModel.todayLogs.collectAsState() val isCompletedToday = todayLogs.any { it.habitId == habitId && it.completed } - var showDeleteDialog by remember { mutableStateOf(false) } + var showDisableDialog by remember { mutableStateOf(false) } - if (showDeleteDialog && habit != null) { + if (showDisableDialog && habit != null) { AlertDialog( - onDismissRequest = { showDeleteDialog = false }, - title = { Text("Delete Habit") }, - text = { Text("Delete \"${habit!!.displayName}\"? All data will be lost.") }, + onDismissRequest = { showDisableDialog = false }, + title = { Text("Disable Habit") }, + text = { Text("Disable \"${habit!!.displayName}\"? It will be greyed out but data is kept.") }, confirmButton = { TextButton(onClick = { - Log.i("HabitDetail", "DELETE '${habit!!.displayName}' id=${habit!!.id}") - viewModel.deleteHabit(habit!!) - showDeleteDialog = false + viewModel.disableHabit(habit!!) + showDisableDialog = false onNavigateBack() - }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }) { Text("Disable", color = MaterialTheme.colorScheme.error) } }, - dismissButton = { TextButton(onClick = { showDeleteDialog = false }) { Text("Cancel") } } + dismissButton = { + TextButton(onClick = { showDisableDialog = false }) { Text("Cancel") } + } ) } @@ -96,16 +82,28 @@ fun HabitDetailScreen( onBack = onNavigateBack, trailing = { Row { - Text("✏️", modifier = Modifier.clickable { onEditHabit(habitId) }.padding(horizontal = 8.dp), - style = MaterialTheme.typography.titleLarge) - Text("🗑️", modifier = Modifier.clickable { showDeleteDialog = true }.padding(horizontal = 8.dp), - style = MaterialTheme.typography.titleLarge) + TextButton(onClick = { onEditHabit(habitId) }) { + Text("Edit", color = MaterialTheme.colorScheme.onPrimary) + } + if (habit?.isActive == true) { + TextButton(onClick = { showDisableDialog = true }) { + Text("−", color = MaterialTheme.colorScheme.onPrimary, + fontWeight = FontWeight.Bold) + } + } else { + TextButton(onClick = { if (habit != null) viewModel.enableHabit(habit!!) }) { + Text("+", color = MaterialTheme.colorScheme.onPrimary, + fontWeight = FontWeight.Bold) + } + } } } ) if (habit == null) { - Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Loading…") } + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Loading…") + } return@Scaffold } @@ -117,12 +115,18 @@ fun HabitDetailScreen( verticalArrangement = Arrangement.spacedBy(16.dp) ) { // Info card - Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(2.dp) + ) { Column(modifier = Modifier.padding(16.dp)) { - Text(h.activityType, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) + Text(h.activityType, style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary) Spacer(modifier = Modifier.height(4.dp)) - Text("Started: ${fmt.format(Date(h.startDate))}", style = MaterialTheme.typography.bodyMedium) - Text("Target: ${h.targetFrequency}x per week", style = MaterialTheme.typography.bodyMedium) + Text("Started: ${fmt.format(Date(h.startDate))}", + style = MaterialTheme.typography.bodyMedium) + Text("Target: ${h.targetFrequency}x per week", + style = MaterialTheme.typography.bodyMedium) if (h.reminderEnabled) { Text("Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${h.reminderMinute.toString().padStart(2, '0')}", style = MaterialTheme.typography.bodyMedium) @@ -130,65 +134,89 @@ fun HabitDetailScreen( } } - // Swipe bar - SwipeBar(isCompletedToday) { - Log.i("HabitDetail", "Swipe '${h.displayName}' id=${h.id} undo=$isCompletedToday") - viewModel.toggleTodayLog(habitId) + // Complete/Undo button + Button( + onClick = { viewModel.toggleTodayLog(habitId) }, + modifier = Modifier.fillMaxWidth().height(52.dp) + ) { + Text( + if (isCompletedToday) "Undo Today" else "Mark Complete", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) } // Streaks Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - StatCard("🔥 Current", "$currentStreak day${if (currentStreak != 1) "s" else ""}", Modifier.weight(1f)) - StatCard("🏆 Longest", "$longestStreak day${if (longestStreak != 1) "s" else ""}", Modifier.weight(1f)) + StatCard("Current Streak", + "$currentStreak day${if (currentStreak != 1) "s" else ""}", + Modifier.weight(1f)) + StatCard("Longest Streak", + "$longestStreak day${if (longestStreak != 1) "s" else ""}", + Modifier.weight(1f)) } // Weekly progress - Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { + Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) { Column(modifier = Modifier.padding(16.dp)) { - Text("Weekly Progress", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - Spacer(modifier = Modifier.height(12.dp)) - LinearProgressIndicator(progress = { weeklyProgress }, - modifier = Modifier.fillMaxWidth().height(12.dp).clip(RoundedCornerShape(6.dp))) - Spacer(modifier = Modifier.height(6.dp)) + Text("Weekly Progress", style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold) + Spacer(modifier = Modifier.height(8.dp)) Text("${(weeklyProgress * 100).toInt()}% of weekly goal", - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) } } // Last 14 days - Text("Last 14 Days", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text("Last 14 Days", style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold) val logDates = logs.filter { it.completed }.map { normalise(it.date) }.toSet() val today = todayMillis() - LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { - items((0..13).map { today - it * 86_400_000L }.reversed()) { day -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + (0..13).map { today - it * 86_400_000L }.reversed().forEach { day -> val done = logDates.contains(day) - Column(horizontalAlignment = Alignment.CenterHorizontally) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.weight(1f) + ) { Box( - modifier = Modifier.size(36.dp).clip(CircleShape).background( - if (done) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant), + modifier = Modifier.size(24.dp) + .background( + if (done) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.surfaceVariant, + shape = androidx.compose.foundation.shape.CircleShape + ), contentAlignment = Alignment.Center ) { - Text(if (done) "✓" else "", - color = if (done) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, - style = MaterialTheme.typography.labelSmall) + Text( + if (done) "✓" else "", + style = MaterialTheme.typography.labelSmall, + color = if (done) MaterialTheme.colorScheme.onPrimary + else MaterialTheme.colorScheme.onSurfaceVariant + ) } - Spacer(modifier = Modifier.height(2.dp)) - Text(SimpleDateFormat("dd", Locale.getDefault()).format(Date(day)), - style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center) + Text( + SimpleDateFormat("dd", Locale.getDefault()).format(Date(day)), + style = MaterialTheme.typography.labelSmall + ) } } } // Total completions val total = logs.count { it.completed } - Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { + Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) { Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { - Text("📊", style = MaterialTheme.typography.headlineMedium) - Spacer(modifier = Modifier.width(12.dp)) Column { - Text("Total Completions", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) + Text("Total Completions", style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold) Text("$total time${if (total != 1) "s" else ""}", - style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) } } } @@ -198,60 +226,32 @@ fun HabitDetailScreen( } } -@Composable -private fun SwipeBar(isCompleted: Boolean, onSwipe: () -> Unit) { - val threshold = 200f - var offsetX by remember { mutableFloatStateOf(0f) } - Box(modifier = Modifier.fillMaxWidth().height(56.dp).clip(RoundedCornerShape(14.dp))) { - Box( - modifier = Modifier.matchParentSize().background( - if (isCompleted) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)), - contentAlignment = Alignment.Center - ) { - Text(if (isCompleted) "Swipe → to Undo" else "Swipe → to Complete", - style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold, - color = if (isCompleted) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.primary) - } - Box( - modifier = Modifier.size(80.dp, 56.dp) - .offset { IntOffset(offsetX.roundToInt(), 0) } - .clip(RoundedCornerShape(14.dp)) - .background(MaterialTheme.colorScheme.primary) - .pointerInput(isCompleted) { - detectHorizontalDragGestures( - onDragEnd = { if (offsetX > threshold) onSwipe(); offsetX = 0f }, - onDragCancel = { offsetX = 0f }, - onHorizontalDrag = { _, d -> offsetX = (offsetX + d).coerceIn(0f, threshold + 50f) }) - }, - contentAlignment = Alignment.Center - ) { - Text(if (isCompleted) "✅" else "→", style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold) - } - } -} - @Composable private fun StatCard(title: String, value: String, modifier: Modifier = Modifier) { - Card(modifier = modifier, shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)) { + Card( + modifier = modifier, + elevation = CardDefaults.cardElevation(2.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer) + ) { Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { - Text(title, style = MaterialTheme.typography.labelMedium, textAlign = TextAlign.Center) + Text(title, style = MaterialTheme.typography.labelMedium) Spacer(modifier = Modifier.height(6.dp)) Text(value, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center) + color = MaterialTheme.colorScheme.primary) } } } private fun normalise(millis: Long): Long { val c = Calendar.getInstance(); c.timeInMillis = millis - c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) + c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0) + c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) return c.timeInMillis } private fun todayMillis(): Long { val c = Calendar.getInstance() - c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) + c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0) + c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) return c.timeInMillis } diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/HomeScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/HomeScreen.kt index 47cdc88..6bc77ce 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/HomeScreen.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/HomeScreen.kt @@ -1,12 +1,11 @@ package com.example.madwellbeingapp.ui.screens -import android.util.Log import androidx.compose.foundation.background -import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize @@ -15,27 +14,23 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults -import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf +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.input.pointer.pointerInput import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.IntOffset @@ -61,59 +56,53 @@ fun HomeScreen( Scaffold { padding -> Column(modifier = Modifier.fillMaxSize().padding(padding)) { - // Extended header with summary + ScreenHeader(title = "Manage Activities", onBack = onNavigateBack) + + // Summary bar Column( modifier = Modifier.fillMaxWidth() - .background(MaterialTheme.colorScheme.primary) - .padding(horizontal = 20.dp, vertical = 24.dp) + .background(MaterialTheme.colorScheme.primaryContainer) + .padding(horizontal = 20.dp, vertical = 12.dp) ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text("←", modifier = Modifier.clickable(onClick = onNavigateBack).padding(end = 16.dp), - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold) - Text("Manage Activities", style = MaterialTheme.typography.headlineSmall, - color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold) - } - Spacer(modifier = Modifier.height(4.dp)) - Text(SimpleDateFormat("EEEE, MMM d", Locale.getDefault()).format(Date()), + Text( + SimpleDateFormat("EEEE, MMM d", Locale.getDefault()).format(Date()), style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.8f)) - Spacer(modifier = Modifier.height(12.dp)) + color = MaterialTheme.colorScheme.onPrimaryContainer + ) val done = activeHabits.count { completedIds.contains(it.id) } - val total = activeHabits.size - Text("$done / $total habits completed today", + Text( + "$done / ${activeHabits.size} habits completed today", style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Medium) - if (total > 0) { - Spacer(modifier = Modifier.height(8.dp)) - LinearProgressIndicator( - progress = { done.toFloat() / total }, - modifier = Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)), - color = MaterialTheme.colorScheme.onPrimary, - trackColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.3f)) - } + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) } - // List or empty state if (activeHabits.isEmpty()) { - Box(modifier = Modifier.fillMaxSize().weight(1f).padding(32.dp), contentAlignment = Alignment.Center) { + Box( + modifier = Modifier.fillMaxSize().weight(1f).padding(32.dp), + contentAlignment = Alignment.Center + ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { - Text("No habits yet!", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text("No habits yet!", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(8.dp)) - Text("Tap the button below to create your first habit", style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)) + Text("Tap the button below to create your first habit", + style = MaterialTheme.typography.bodyMedium) } } } else { LazyColumn( - modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + modifier = Modifier.weight(1f).fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp) ) { items(activeHabits, key = { it.id }) { habit -> + val completed = completedIds.contains(habit.id) SwipeHabitCard( habit = habit, - completed = completedIds.contains(habit.id), - onSwipe = { viewModel.toggleTodayLog(habit.id) }, + completed = completed, + onSwipeRight = { viewModel.toggleTodayLog(habit.id) }, + onSwipeLeft = { viewModel.disableHabit(habit) }, onClick = { onHabitClick(habit.id) }, viewModel = viewModel ) @@ -123,91 +112,128 @@ fun HomeScreen( Button( onClick = onAddHabit, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp).height(52.dp), + modifier = Modifier.fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp).height(52.dp), shape = RoundedCornerShape(14.dp) ) { - Text("+ Add New Habit", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text("+ Add New Habit", style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold) } } } } -/** Habit card with swipe-to-complete gesture. */ +/** Habit card with swipe-right-to-complete, swipe-left-to-disable, and a − button. */ @Composable private fun SwipeHabitCard( - habit: Habit, completed: Boolean, onSwipe: () -> Unit, - onClick: () -> Unit, viewModel: HabitViewModel + habit: Habit, completed: Boolean, onSwipeRight: () -> Unit, + onSwipeLeft: () -> Unit, onClick: () -> Unit, viewModel: HabitViewModel ) { val weeklyProgress by viewModel.weeklyProgress(habit.id).collectAsState(initial = 0f) val threshold = 150f - var offsetX by remember { mutableFloatStateOf(0f) } + var offsetX by remember { mutableStateOf(0f) } - Box(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp))) { - // Swipe background + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + // Right-swipe reveal (complete / undo) Box( - modifier = Modifier.matchParentSize().background( - if (completed) MaterialTheme.colorScheme.error.copy(alpha = 0.2f) - else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)), + modifier = Modifier.matchParentSize() + .background( + if (completed) MaterialTheme.colorScheme.error.copy(alpha = 0.2f) + else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f), + shape = RoundedCornerShape(16.dp) + ), contentAlignment = Alignment.CenterStart ) { Text( - if (completed) " ← Undo" else " Swipe → to Complete", + if (completed) " ← Undo" else " → Complete", modifier = Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold, - color = if (completed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary) + color = if (completed) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.primary + ) } + // Left-swipe reveal (disable) + Box( + modifier = Modifier.matchParentSize() + .background( + MaterialTheme.colorScheme.error.copy(alpha = 0.15f), + shape = RoundedCornerShape(16.dp) + ), + contentAlignment = Alignment.CenterEnd + ) { + Text( + "Disable ← ", + modifier = Modifier.padding(end = 16.dp), + style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.error + ) + } + // Sliding card Card( + onClick = onClick, modifier = Modifier.fillMaxWidth() .offset { IntOffset(offsetX.roundToInt(), 0) } .pointerInput(completed) { detectHorizontalDragGestures( onDragEnd = { - if (offsetX > threshold) { - Log.d("SwipeGesture", "Swiped '${habit.displayName}'") - onSwipe() - } + if (offsetX > threshold) onSwipeRight() + else if (offsetX < -threshold) onSwipeLeft() offsetX = 0f }, onDragCancel = { offsetX = 0f }, - onHorizontalDrag = { _, d -> offsetX = (offsetX + d).coerceIn(0f, threshold + 50f) } + onHorizontalDrag = { _, d -> + offsetX = (offsetX + d).coerceIn(-(threshold + 50f), threshold + 50f) + } ) - }.clickable(onClick = onClick), + }, shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), colors = CardDefaults.cardColors( containerColor = if (completed) MaterialTheme.colorScheme.primaryContainer - else MaterialTheme.colorScheme.surface) + else MaterialTheme.colorScheme.surface + ) ) { - Row(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) { - Box( - modifier = Modifier.size(44.dp).clip(CircleShape).background( - if (completed) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center - ) { - Text(if (completed) "✓" else "", - color = if (completed) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, - fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium) - } - Spacer(modifier = Modifier.width(14.dp)) - Column(modifier = Modifier.weight(1f)) { - Text(habit.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - Spacer(modifier = Modifier.height(2.dp)) - Text(habit.activityType + " • ${habit.targetFrequency}x/week", - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Spacer(modifier = Modifier.height(8.dp)) - LinearProgressIndicator( - progress = { weeklyProgress }, - modifier = Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)), - color = MaterialTheme.colorScheme.primary, trackColor = MaterialTheme.colorScheme.surfaceVariant) - Spacer(modifier = Modifier.height(2.dp)) - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - Text("Weekly: ${(weeklyProgress * 100).toInt()}%", + Column(modifier = Modifier.padding(16.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(modifier = Modifier.weight(1f)) { + Text(habit.displayName, style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold) + Text( + habit.activityType + " • ${habit.targetFrequency}x/week", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "Weekly: ${(weeklyProgress * 100).toInt()}%", style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)) - if (!completed) Text("Swipe → to complete", + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + // Minus button for quick disable + Button( + onClick = onSwipeLeft, + modifier = Modifier.size(36.dp), + shape = RoundedCornerShape(8.dp), + contentPadding = PaddingValues(0.dp) + ) { + Text("−", style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold) + } + } + Spacer(modifier = Modifier.height(4.dp)) + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + if (!completed) { + Text("→ complete ← disable", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)) + } else { + Text("→ undo", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error.copy(alpha = 0.6f)) } } } diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/LandingScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/LandingScreen.kt index 75c6210..6d7fd39 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/LandingScreen.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/LandingScreen.kt @@ -32,7 +32,8 @@ import androidx.compose.ui.unit.dp fun LandingScreen( onAllActivities: () -> Unit, onManageActivities: () -> Unit, - onActiveOnly: () -> Unit + onActiveOnly: () -> Unit, + onCalendar: () -> Unit ) { Box( modifier = Modifier @@ -69,6 +70,8 @@ fun LandingScreen( LandingButton("Manage Activities", onManageActivities) Spacer(modifier = Modifier.height(16.dp)) LandingButton("Active Only", onActiveOnly) + Spacer(modifier = Modifier.height(16.dp)) + LandingButton("Calendar", onCalendar) } } } diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/SharedComponents.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/SharedComponents.kt index ea95bfa..4ab04cc 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/screens/SharedComponents.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/SharedComponents.kt @@ -1,7 +1,6 @@ package com.example.madwellbeingapp.ui.screens import androidx.compose.foundation.background -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -12,30 +11,22 @@ 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.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults -import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue 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.text.font.FontWeight import androidx.compose.ui.unit.dp import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel -// ───────────────────────────────────────────────────────────── -// Reusable composables shared across multiple screens. -// ───────────────────────────────────────────────────────────── - -/** Standard header bar with a ← back button and a title. */ +/** Standard header bar with a back button and a title. */ @Composable fun ScreenHeader( title: String, @@ -46,7 +37,7 @@ fun ScreenHeader( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.primary) - .padding(horizontal = 16.dp, vertical = 16.dp) + .padding(horizontal = 8.dp, vertical = 8.dp) ) { Row( modifier = Modifier.fillMaxWidth(), @@ -54,15 +45,14 @@ fun ScreenHeader( horizontalArrangement = Arrangement.SpaceBetween ) { Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = "←", - modifier = Modifier - .clickable(onClick = onBack) - .padding(end = 12.dp), - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onPrimary, - fontWeight = FontWeight.Bold - ) + TextButton(onClick = onBack) { + Text( + text = "←", + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onPrimary, + fontWeight = FontWeight.Bold + ) + } Text( text = title, style = MaterialTheme.typography.titleLarge, @@ -77,45 +67,39 @@ fun ScreenHeader( /** * Standard habit card used on list screens. - * - * Shows a status circle, display name, activity type, frequency, and - * a weekly progress bar. Customisable via [circleColor], [circleText], - * and [containerColor]. */ @Composable fun HabitCard( habit: Habit, viewModel: HabitViewModel, onClick: () -> Unit, - circleColor: Color = MaterialTheme.colorScheme.surfaceVariant, + circleColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surfaceVariant, circleText: String = "", - circleTextColor: Color = MaterialTheme.colorScheme.onSurfaceVariant, - containerColor: Color = MaterialTheme.colorScheme.surface, - badge: @Composable (() -> Unit)? = null + circleTextColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.onSurfaceVariant, + containerColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surface, + contentAlpha: Float = 1f, + badge: @Composable (() -> Unit)? = null, + trailing: @Composable (() -> Unit)? = null ) { val weeklyProgress by viewModel.weeklyProgress(habit.id) .collectAsState(initial = 0f) Card( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick), - shape = RoundedCornerShape(16.dp), + onClick = onClick, + modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), colors = CardDefaults.cardColors(containerColor = containerColor) ) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { - // Status circle Box( - modifier = Modifier - .size(44.dp) - .clip(CircleShape) - .background(circleColor), + modifier = Modifier.size(44.dp) + .background( + circleColor.copy(alpha = contentAlpha), + shape = androidx.compose.foundation.shape.CircleShape + ), contentAlignment = Alignment.Center ) { Text( @@ -133,7 +117,8 @@ fun HabitCard( Text( text = habit.displayName, style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface.copy(alpha = contentAlpha) ) if (badge != null) { Spacer(modifier = Modifier.width(8.dp)) @@ -144,26 +129,20 @@ fun HabitCard( Text( text = habit.activityType + " • ${habit.targetFrequency}x/week", style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha) ) - Spacer(modifier = Modifier.height(8.dp)) - LinearProgressIndicator( - progress = { weeklyProgress }, - modifier = Modifier - .fillMaxWidth() - .height(6.dp) - .clip(RoundedCornerShape(3.dp)), - color = MaterialTheme.colorScheme.primary, - trackColor = MaterialTheme.colorScheme.surfaceVariant, - ) - Spacer(modifier = Modifier.height(2.dp)) + Spacer(modifier = Modifier.height(4.dp)) Text( text = "Weekly: ${(weeklyProgress * 100).toInt()}%", style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f * contentAlpha) ) } + + if (trailing != null) { + Spacer(modifier = Modifier.width(8.dp)) + trailing() + } } } } - diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/viewmodel/HabitViewModel.kt b/app/src/main/java/com/example/madwellbeingapp/ui/viewmodel/HabitViewModel.kt index d733289..0901970 100644 --- a/app/src/main/java/com/example/madwellbeingapp/ui/viewmodel/HabitViewModel.kt +++ b/app/src/main/java/com/example/madwellbeingapp/ui/viewmodel/HabitViewModel.kt @@ -1,22 +1,13 @@ package com.example.madwellbeingapp.ui.viewmodel -import android.Manifest import android.app.Application -import android.app.Notification -import android.app.NotificationManager -import android.content.Context -import android.content.pm.PackageManager -import android.os.Build -import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.example.madwellbeingapp.HabitApp -import com.example.madwellbeingapp.R import com.example.madwellbeingapp.data.model.ActivityType import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.HabitLog import com.example.madwellbeingapp.data.repository.HabitRepository -import com.example.madwellbeingapp.notification.HabitNotificationScheduler import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -37,8 +28,6 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { (application as HabitApp).repository companion object { - private const val TAG = "HabitViewModel" - /** * Converts text to title-case: lowercase everything, then uppercase * the first letter of each word. Handles parentheses properly so @@ -83,22 +72,14 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { } val existing = repository.findActivityTypeByName(formatted) if (existing != null) { - Log.w(TAG, "ACTIVITY TYPE DUPLICATE: '$formatted' already exists") onResult(false) return@launch } repository.addActivityType(ActivityType(name = formatted)) - Log.i(TAG, "ACTIVITY TYPE CREATED: '$formatted'") onResult(true) } } - fun deleteActivityType(activityType: ActivityType) { - viewModelScope.launch { - repository.deleteActivityType(activityType) - Log.i(TAG, "ACTIVITY TYPE DELETED: '${activityType.name}'") - } - } // ── All habits ────────────────────────────────────────── val allHabits: StateFlow> = repository.allHabits @@ -153,38 +134,40 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { fun selectHabit(habitId: Int) { _selectedHabitId.value = habitId - computeStreaks(habitId) - } - - private fun computeStreaks(habitId: Int) { viewModelScope.launch { - val logs = repository.getCompletedLogsDesc(habitId) - if (logs.isEmpty()) { - _currentStreak.value = 0 - _longestStreak.value = 0 - return@launch - } - val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending() - var current = 0 - val today = todayStart - val yesterday = today - 86_400_000L - if (days.first() == today || days.first() == yesterday) { - var expected = days.first() - for (day in days) { - if (day == expected) { current++; expected -= 86_400_000L } else break - } - } - var longest = 1; var streak = 1 - for (i in 1 until days.size) { - if (days[i] == days[i - 1] - 86_400_000L) { - streak++; if (streak > longest) longest = streak - } else streak = 1 - } + val (current, longest) = computeStreakPair(habitId) _currentStreak.value = current _longestStreak.value = longest } } + /** Returns (currentStreak, longestStreak) for a habit. */ + private suspend fun computeStreakPair(habitId: Int): Pair { + val logs = repository.getCompletedLogsDesc(habitId) + if (logs.isEmpty()) return 0 to 0 + val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending() + // Current streak + var current = 0 + val today = todayStart + if (days.first() == today || days.first() == today - 86_400_000L) { + var expected = days.first() + for (day in days) { + if (day == expected) { current++; expected -= 86_400_000L } else break + } + } + // Longest streak + var longest = 1; var streak = 1 + for (i in 1 until days.size) { + if (days[i] == days[i - 1] - 86_400_000L) { + streak++; if (streak > longest) longest = streak + } else streak = 1 + } + return current to longest + } + + /** Public accessor for calendar/other screens needing just current streak. */ + suspend fun computeStreakForHabit(habitId: Int): Int = computeStreakPair(habitId).first + // ── Weekly progress for a habit ───────────────────────── fun weeklyProgress(habitId: Int): Flow { return repository.getLogsForHabit(habitId).map { logs -> @@ -220,7 +203,6 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { val formattedType = toTitleCase(activityType.trim()) if (isDuplicate(formattedName, formattedDetails)) { - Log.w(TAG, "DUPLICATE BLOCKED: '$formattedName($formattedDetails)' already exists") onResult(false) return@launch } @@ -235,13 +217,7 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { reminderHour = reminderHour, reminderMinute = reminderMinute ) - val id = repository.insertHabit(habit).toInt() - Log.i(TAG, "HABIT CREATED: name='${habit.displayName}', type='$formattedType', frequency=${targetFrequency}x/week, id=$id") - if (reminderEnabled) { - HabitNotificationScheduler.schedule( - getApplication(), id, habit.displayName, reminderHour, reminderMinute - ) - } + repository.insertHabit(habit) onResult(true) } } @@ -254,80 +230,35 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { activityType = toTitleCase(habit.activityType.trim()) ) repository.updateHabit(updated) - Log.i(TAG, "HABIT UPDATED: name='${updated.displayName}', id=${updated.id}, type='${updated.activityType}', frequency=${updated.targetFrequency}x/week") - if (updated.reminderEnabled) { - HabitNotificationScheduler.schedule( - getApplication(), updated.id, updated.displayName, - updated.reminderHour, updated.reminderMinute - ) - } else { - HabitNotificationScheduler.cancel(getApplication(), updated.id) - } } } - fun deleteHabit(habit: Habit) { + fun disableHabit(habit: Habit) { viewModelScope.launch { - HabitNotificationScheduler.cancel(getApplication(), habit.id) - repository.deleteHabit(habit) - Log.i(TAG, "HABIT DELETED: name='${habit.displayName}', id=${habit.id}") + val updated = habit.copy(isActive = false) + repository.updateHabit(updated) + } + } + + fun enableHabit(habit: Habit) { + viewModelScope.launch { + val updated = habit.copy(isActive = true) + repository.updateHabit(updated) } } // ── Daily logging ─────────────────────────────────────── fun toggleTodayLog(habitId: Int) { viewModelScope.launch { - val existing = repository.getLogForDate(habitId, todayStart) - val habit = repository.getHabitByIdOnce(habitId) repository.toggleLog(habitId, todayStart) - if (existing == null) { - Log.i(TAG, "HABIT COMPLETED: habit='${habit?.displayName}' (id=$habitId), date=$todayStart") - } else { - Log.i(TAG, "HABIT UNCOMPLETION: habit='${habit?.displayName}' (id=$habitId), date=$todayStart") + if (_selectedHabitId.value == habitId) { + val (c, l) = computeStreakPair(habitId) + _currentStreak.value = c + _longestStreak.value = l } - if (_selectedHabitId.value == habitId) computeStreaks(habitId) - checkStreakCelebration(habitId) } } - private suspend fun checkStreakCelebration(habitId: Int) { - val logs = repository.getCompletedLogsDesc(habitId) - if (logs.isEmpty()) return - val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending() - if (days.first() != todayStart) return - var streak = 0; var expected = todayStart - for (day in days) { - if (day == expected) { streak++; expected -= 86_400_000L } else break - } - if (streak > 0 && streak % 7 == 0) sendCelebration(habitId, streak) - } - - private suspend fun sendCelebration(habitId: Int, streak: Int) { - val habit = repository.getHabitByIdOnce(habitId) ?: return - val ctx = getApplication() - Log.i(TAG, "STREAK MILESTONE: habit='${habit.displayName}', streak=$streak days!") - val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - Notification.Builder(ctx, HabitApp.CHANNEL_ID) - .setSmallIcon(R.drawable.ic_launcher_foreground) - .setContentTitle("Streak Milestone!") - .setContentText("$streak-day streak on \"${habit.displayName}\"!") - .setAutoCancel(true).build() - } else { - @Suppress("DEPRECATION") - Notification.Builder(ctx) - .setSmallIcon(R.drawable.ic_launcher_foreground) - .setContentTitle("Streak Milestone!") - .setContentText("$streak-day streak on \"${habit.displayName}\"!") - .setAutoCancel(true).build() - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - if (ctx.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) - != PackageManager.PERMISSION_GRANTED) return - } - val manager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - manager.notify(habitId + 10_000, notification) - } - // ── Helpers ────────────────────────────────────────────── private fun normaliseToDay(millis: Long): Long { val cal = Calendar.getInstance() @@ -336,4 +267,8 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) { cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0) return cal.timeInMillis } + + // ── Calendar support ──────────────────────────────────── + fun getLogsBetween(startDate: Long, endDate: Long): Flow> = + repository.getLogsBetween(startDate, endDate) } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5ddd6ac..aefa909 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,6 +12,7 @@ room = "2.7.1" lifecycleViewmodelCompose = "2.6.1" ksp = "2.3.2" coreKtxVersion = "1.17.0" +navigation3 = "1.0.0" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } @@ -33,6 +34,8 @@ androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" } core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtxVersion" } +androidx-navigation3 = { group = "androidx.navigation3", name = "navigation3-runtime", version.ref = "navigation3" } +androidx-navigation3-ui = { group = "androidx.navigation3", name = "navigation3-ui", version.ref = "navigation3" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } diff --git a/gradlew b/gradlew old mode 100644 new mode 100755