diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 0000000..6e0a661
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+Mad Wellbeing App
\ No newline at end of file
diff --git a/.idea/appInsightsSettings.xml b/.idea/appInsightsSettings.xml
new file mode 100644
index 0000000..7b59ca0
--- /dev/null
+++ b/.idea/appInsightsSettings.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..b86273d
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/copilot.data.migration.ask2agent.xml b/.idea/copilot.data.migration.ask2agent.xml
new file mode 100644
index 0000000..1f2ea11
--- /dev/null
+++ b/.idea/copilot.data.migration.ask2agent.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml
new file mode 100644
index 0000000..91f9558
--- /dev/null
+++ b/.idea/deviceManager.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..02c4aa5
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 8cd0a74..64ab646 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -56,8 +56,6 @@ dependencies {
implementation(libs.core.ktx)
ksp(libs.androidx.room.compiler)
- // Navigation Compose
- implementation(libs.androidx.navigation.compose)
// ViewModel Compose
implementation(libs.androidx.lifecycle.viewmodel.compose)
diff --git a/app/src/androidTest/java/com/example/madwellbeingapp/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/example/madwellbeingapp/ExampleInstrumentedTest.kt
new file mode 100644
index 0000000..df0da86
--- /dev/null
+++ b/app/src/androidTest/java/com/example/madwellbeingapp/ExampleInstrumentedTest.kt
@@ -0,0 +1,24 @@
+package com.example.madwellbeingapp
+
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.ext.junit.runners.AndroidJUnit4
+
+import org.junit.Test
+import org.junit.runner.RunWith
+
+import org.junit.Assert.*
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+@RunWith(AndroidJUnit4::class)
+class ExampleInstrumentedTest {
+ @Test
+ fun useAppContext() {
+ // Context of the app under test.
+ val appContext = InstrumentationRegistry.getInstrumentation().targetContext
+ assertEquals("com.example.madwellbeingapp", appContext.packageName)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt b/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt
index bd9dc69..5b65b7e 100644
--- a/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/HabitApp.kt
@@ -14,7 +14,7 @@ class HabitApp : Application() {
val database by lazy { HabitDatabase.getDatabase(this) }
val repository by lazy {
- HabitRepository(database.habitDao(), database.habitLogDao())
+ HabitRepository(database.habitDao(), database.habitLogDao(), database.activityTypeDao())
}
override fun onCreate() {
diff --git a/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt b/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt
index e71aa53..a6d41d3 100644
--- a/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/MainActivity.kt
@@ -11,16 +11,15 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
-import androidx.core.content.ContextCompat
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.remember
import androidx.lifecycle.viewmodel.compose.viewModel
-import androidx.navigation.NavType
-import androidx.navigation.compose.NavHost
-import androidx.navigation.compose.composable
-import androidx.navigation.compose.rememberNavController
-import androidx.navigation.navArgument
+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.HabitDetailScreen
import com.example.madwellbeingapp.ui.screens.HomeScreen
+import com.example.madwellbeingapp.ui.screens.LandingScreen
import com.example.madwellbeingapp.ui.theme.MadWellbeingAppTheme
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
@@ -35,7 +34,7 @@ class MainActivity : ComponentActivity() {
// Request notification permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
+ if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
@@ -50,55 +49,100 @@ class MainActivity : ComponentActivity() {
}
}
+/**
+ * Simple sealed class representing each screen destination.
+ * We avoid using Navigation Compose library and use manual state-based navigation.
+ */
+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 AddHabit : Screen()
+ data class EditHabit(val habitId: Int) : Screen()
+ data class HabitDetail(val habitId: Int) : Screen()
+}
+
@Composable
fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) {
- val navController = rememberNavController()
+ // Manual back-stack — starts on the Landing screen
+ val backStack = remember { mutableStateListOf(Screen.Landing) }
+ val currentScreen = backStack.last()
- NavHost(navController = navController, startDestination = "home") {
+ fun navigateTo(screen: Screen) {
+ backStack.add(screen)
+ }
- composable("home") {
- HomeScreen(
- viewModel = viewModel,
- onAddHabit = { navController.navigate("add_habit") },
- onHabitClick = { id -> navController.navigate("habit_detail/$id") }
+ 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) }
)
}
- composable("add_habit") {
+ 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 = { navController.popBackStack() }
+ onNavigateBack = { navigateBack() }
)
}
- composable(
- route = "edit_habit/{habitId}",
- arguments = listOf(navArgument("habitId") { type = NavType.IntType })
- ) { backStackEntry ->
- val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
- // Observe the habit so the form is pre-populated
+ is Screen.EditHabit -> {
val allHabits by viewModel.allHabits.collectAsState()
- val habit = allHabits.find { it.id == habitId }
+ val habit = allHabits.find { it.id == currentScreen.habitId }
if (habit != null) {
AddEditHabitScreen(
viewModel = viewModel,
existingHabit = habit,
- onNavigateBack = { navController.popBackStack() }
+ onNavigateBack = { navigateBack() }
)
}
}
- composable(
- route = "habit_detail/{habitId}",
- arguments = listOf(navArgument("habitId") { type = NavType.IntType })
- ) { backStackEntry ->
- val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
+ is Screen.HabitDetail -> {
HabitDetailScreen(
- habitId = habitId,
+ habitId = currentScreen.habitId,
viewModel = viewModel,
- onNavigateBack = { navController.popBackStack() },
- onEditHabit = { id -> navController.navigate("edit_habit/$id") }
+ onNavigateBack = { navigateBack() },
+ onEditHabit = { id -> navigateTo(Screen.EditHabit(id)) }
)
}
}
diff --git a/app/src/main/java/com/example/madwellbeingapp/data/Converters.kt b/app/src/main/java/com/example/madwellbeingapp/data/Converters.kt
index fb2cc6a..e2c344c 100644
--- a/app/src/main/java/com/example/madwellbeingapp/data/Converters.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/data/Converters.kt
@@ -1,18 +1,7 @@
package com.example.madwellbeingapp.data
-import androidx.room.TypeConverter
-import com.example.madwellbeingapp.data.model.HabitCategory
-
-class Converters {
-
- @TypeConverter
- fun fromCategory(category: HabitCategory): String {
- return category.name
- }
-
- @TypeConverter
- fun toCategory(value: String): HabitCategory {
- return HabitCategory.valueOf(value)
- }
-}
-
+/**
+ * Room type converters. Currently empty since HabitCategory enum was removed.
+ * Kept in case future types need conversion.
+ */
+class Converters
diff --git a/app/src/main/java/com/example/madwellbeingapp/data/HabitDatabase.kt b/app/src/main/java/com/example/madwellbeingapp/data/HabitDatabase.kt
index c51c84b..4e86a85 100644
--- a/app/src/main/java/com/example/madwellbeingapp/data/HabitDatabase.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/data/HabitDatabase.kt
@@ -4,18 +4,23 @@ import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
-import androidx.room.TypeConverters
+import com.example.madwellbeingapp.data.dao.ActivityTypeDao
import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao
+import com.example.madwellbeingapp.data.model.ActivityType
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitLog
-@Database(entities = [Habit::class, HabitLog::class], version = 1, exportSchema = false)
-@TypeConverters(Converters::class)
+@Database(
+ entities = [Habit::class, HabitLog::class, ActivityType::class],
+ version = 3,
+ exportSchema = false
+)
abstract class HabitDatabase : RoomDatabase() {
abstract fun habitDao(): HabitDao
abstract fun habitLogDao(): HabitLogDao
+ abstract fun activityTypeDao(): ActivityTypeDao
companion object {
@Volatile
@@ -27,11 +32,12 @@ abstract class HabitDatabase : RoomDatabase() {
context.applicationContext,
HabitDatabase::class.java,
"habit_database"
- ).build()
+ )
+ .fallbackToDestructiveMigration(true)
+ .build()
INSTANCE = instance
instance
}
}
}
}
-
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
new file mode 100644
index 0000000..c108453
--- /dev/null
+++ b/app/src/main/java/com/example/madwellbeingapp/data/dao/ActivityTypeDao.kt
@@ -0,0 +1,26 @@
+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
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+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>
+
+ /** Check if an activity type with this name already exists (case-insensitive). */
+ @Query("SELECT * FROM activity_types WHERE LOWER(name) = LOWER(:name) LIMIT 1")
+ suspend fun findByName(name: String): ActivityType?
+}
+
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 b4dead5..05a2bf7 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
@@ -2,21 +2,16 @@ package com.example.madwellbeingapp.data.dao
import androidx.room.Dao
import androidx.room.Delete
-import androidx.room.Insert
-import androidx.room.OnConflictStrategy
import androidx.room.Query
-import androidx.room.Update
+import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.Habit
import kotlinx.coroutines.flow.Flow
@Dao
interface HabitDao {
- @Insert(onConflict = OnConflictStrategy.REPLACE)
- suspend fun insert(habit: Habit): Long
-
- @Update
- suspend fun update(habit: Habit): Int
+ @Upsert
+ suspend fun upsert(habit: Habit): Long
@Delete
suspend fun delete(habit: Habit): Int
@@ -29,4 +24,8 @@ interface HabitDao {
@Query("SELECT * FROM habits WHERE id = :id")
suspend fun getHabitByIdOnce(id: Int): Habit?
+
+ /** Check if a habit with the same name+details already exists (case-insensitive). */
+ @Query("SELECT * FROM habits WHERE LOWER(name) = LOWER(:name) AND LOWER(details) = LOWER(:details) LIMIT 1")
+ suspend fun findDuplicate(name: String, details: String): Habit?
}
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 738febc..908140f 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
@@ -1,17 +1,16 @@
package com.example.madwellbeingapp.data.dao
import androidx.room.Dao
-import androidx.room.Insert
-import androidx.room.OnConflictStrategy
import androidx.room.Query
+import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.HabitLog
import kotlinx.coroutines.flow.Flow
@Dao
interface HabitLogDao {
- @Insert(onConflict = OnConflictStrategy.REPLACE)
- suspend fun insert(log: HabitLog): Long
+ @Upsert
+ suspend fun upsert(log: HabitLog): Long
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId ORDER BY date DESC")
fun getLogsForHabit(habitId: Int): Flow>
diff --git a/app/src/main/java/com/example/madwellbeingapp/data/model/ActivityType.kt b/app/src/main/java/com/example/madwellbeingapp/data/model/ActivityType.kt
new file mode 100644
index 0000000..c5136ad
--- /dev/null
+++ b/app/src/main/java/com/example/madwellbeingapp/data/model/ActivityType.kt
@@ -0,0 +1,15 @@
+package com.example.madwellbeingapp.data.model
+
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+/**
+ * A user-created activity type (e.g. "Gym", "Running", "Yoga").
+ * These populate the dropdown when creating a new habit.
+ */
+@Entity(tableName = "activity_types")
+data class ActivityType(
+ @PrimaryKey(autoGenerate = true) val id: Int = 0,
+ val name: String
+)
+
diff --git a/app/src/main/java/com/example/madwellbeingapp/data/model/Habit.kt b/app/src/main/java/com/example/madwellbeingapp/data/model/Habit.kt
index f06a4e0..ddd97c9 100644
--- a/app/src/main/java/com/example/madwellbeingapp/data/model/Habit.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/data/model/Habit.kt
@@ -5,23 +5,24 @@ import androidx.room.PrimaryKey
/**
* Represents a habit tracked by the user.
+ * [name] is the activity type name chosen from the user-created dropdown (e.g. "Gym").
+ * [details] is optional extra info typed by the user (e.g. "Legs", "5K").
+ * The display name combines them: "Gym(Legs)" when details is present, or just "Gym".
*/
@Entity(tableName = "habits")
data class Habit(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String,
- val category: HabitCategory,
+ val details: String = "",
+ val activityType: String = "", // the user-created activity type name
val startDate: Long, // epoch millis – auto-set on creation
val targetFrequency: Int, // times per week the user wants to complete this habit
val reminderEnabled: Boolean = true,
val reminderHour: Int = 9, // default 09:00
- val reminderMinute: Int = 0
-)
-
-enum class HabitCategory(val displayName: String) {
- HEALTH("Health"),
- STUDY("Study"),
- FITNESS("Fitness"),
- WELLBEING("Wellbeing")
+ val reminderMinute: Int = 0,
+ val isActive: Boolean = true
+) {
+ /** Returns the formatted display name: "Name(Details)" or just "Name". */
+ val displayName: String
+ get() = if (details.isBlank()) name else "$name($details)"
}
-
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 9b52798..4ef4fb5 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
@@ -1,18 +1,21 @@
package com.example.madwellbeingapp.data.repository
+import com.example.madwellbeingapp.data.dao.ActivityTypeDao
import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao
+import com.example.madwellbeingapp.data.model.ActivityType
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitLog
import kotlinx.coroutines.flow.Flow
/**
- * Single source of truth for habit and log data.
+ * Single source of truth for habit, log, and activity-type data.
* Abstracts the data sources away from the ViewModels.
*/
class HabitRepository(
private val habitDao: HabitDao,
- private val habitLogDao: HabitLogDao
+ private val habitLogDao: HabitLogDao,
+ private val activityTypeDao: ActivityTypeDao
) {
// ── Habits ──────────────────────────────────────────────
val allHabits: Flow> = habitDao.getAllHabits()
@@ -21,12 +24,28 @@ class HabitRepository(
suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id)
- suspend fun insertHabit(habit: Habit): Long = habitDao.insert(habit)
+ suspend fun insertHabit(habit: Habit): Long = habitDao.upsert(habit)
- suspend fun updateHabit(habit: Habit) = habitDao.update(habit)
+ 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? =
+ habitDao.findDuplicate(name, details)
+
+ // ── Activity Types ──────────────────────────────────────
+ val allActivityTypes: Flow> = activityTypeDao.getAll()
+
+ 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)
+
// ── Logs ────────────────────────────────────────────────
fun getLogsForHabit(habitId: Int): Flow> =
habitLogDao.getLogsForHabit(habitId)
@@ -42,7 +61,7 @@ class HabitRepository(
if (existing != null) {
habitLogDao.deleteLogForDate(habitId, date)
} else {
- habitLogDao.insert(HabitLog(habitId = habitId, date = date, completed = true))
+ habitLogDao.upsert(HabitLog(habitId = habitId, date = date, completed = true))
}
}
@@ -52,4 +71,3 @@ class HabitRepository(
suspend fun getCompletedLogsDesc(habitId: Int): List =
habitLogDao.getCompletedLogsDesc(habitId)
}
-
diff --git a/app/src/main/java/com/example/madwellbeingapp/notification/HabitReminderReceiver.kt b/app/src/main/java/com/example/madwellbeingapp/notification/HabitReminderReceiver.kt
index 5167fd9..3933528 100644
--- a/app/src/main/java/com/example/madwellbeingapp/notification/HabitReminderReceiver.kt
+++ b/app/src/main/java/com/example/madwellbeingapp/notification/HabitReminderReceiver.kt
@@ -1,20 +1,22 @@
package com.example.madwellbeingapp.notification
import android.Manifest
+import android.app.Notification
+import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
-import androidx.core.app.NotificationCompat
-import androidx.core.app.NotificationManagerCompat
-import androidx.core.content.ContextCompat
+import android.os.Build
+import android.util.Log
import com.example.madwellbeingapp.HabitApp
import com.example.madwellbeingapp.MainActivity
import com.example.madwellbeingapp.R
/**
* Receives the alarm broadcast and posts a notification for the habit.
+ * Uses native android.app.Notification.Builder instead of NotificationCompat.
*/
class HabitReminderReceiver : BroadcastReceiver() {
@@ -22,6 +24,8 @@ class HabitReminderReceiver : BroadcastReceiver() {
val habitId = intent.getIntExtra("habit_id", -1)
val habitName = intent.getStringExtra("habit_name") ?: "your habit"
+ Log.d("HabitReminder", "Reminder fired for habit '$habitName' (id=$habitId)")
+
// Tap notification → open app
val tapIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
@@ -31,20 +35,35 @@ class HabitReminderReceiver : BroadcastReceiver() {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
- val notification = NotificationCompat.Builder(context, HabitApp.CHANNEL_ID)
- .setSmallIcon(R.drawable.ic_launcher_foreground)
- .setContentTitle("Habit Reminder 🔔")
- .setContentText("Time to work on \"$habitName\"!")
- .setPriority(NotificationCompat.PRIORITY_DEFAULT)
- .setContentIntent(tapPending)
- .setAutoCancel(true)
- .build()
-
- if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
- == PackageManager.PERMISSION_GRANTED
- ) {
- NotificationManagerCompat.from(context).notify(habitId, notification)
+ val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Notification.Builder(context, HabitApp.CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_launcher_foreground)
+ .setContentTitle("Habit Reminder")
+ .setContentText("Time to work on \"$habitName\"!")
+ .setContentIntent(tapPending)
+ .setAutoCancel(true)
+ .build()
+ } else {
+ @Suppress("DEPRECATION")
+ Notification.Builder(context)
+ .setSmallIcon(R.drawable.ic_launcher_foreground)
+ .setContentTitle("Habit Reminder")
+ .setContentText("Time to work on \"$habitName\"!")
+ .setContentIntent(tapPending)
+ .setAutoCancel(true)
+ .build()
}
+
+ // Check permission on Android 13+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
+ != PackageManager.PERMISSION_GRANTED
+ ) {
+ return
+ }
+ }
+
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ manager.notify(habitId, notification)
}
}
-
diff --git a/app/src/main/java/com/example/madwellbeingapp/ui/screens/ActiveOnlyScreen.kt b/app/src/main/java/com/example/madwellbeingapp/ui/screens/ActiveOnlyScreen.kt
new file mode 100644
index 0000000..ddd203b
--- /dev/null
+++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/ActiveOnlyScreen.kt
@@ -0,0 +1,198 @@
+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
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.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.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.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+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
+
+/**
+ * Shows only habits that are still active and NOT yet completed today.
+ * These are the ones the user still needs to do.
+ */
+@Composable
+fun ActiveOnlyScreen(
+ viewModel: HabitViewModel,
+ onNavigateBack: () -> Unit,
+ onHabitClick: (Int) -> Unit
+) {
+ val activeHabits by viewModel.activeHabitsNotCompletedToday.collectAsState()
+
+ Scaffold { padding ->
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding)
+ ) {
+ // Header
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(MaterialTheme.colorScheme.tertiary)
+ .padding(horizontal = 16.dp, vertical = 16.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = "←",
+ modifier = Modifier
+ .clickable(onClick = onNavigateBack)
+ .padding(end = 16.dp),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onTertiary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = "Active — To Do",
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onTertiary,
+ fontWeight = FontWeight.Bold
+ )
+ }
+ }
+
+ if (activeHabits.isEmpty()) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(32.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = "All caught up!",
+ style = MaterialTheme.typography.titleMedium,
+ color = MaterialTheme.colorScheme.primary,
+ fontWeight = FontWeight.Bold
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ Text(
+ text = "You've completed all your active habits for today.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ } else {
+ LazyColumn(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ items(activeHabits, key = { it.id }) { habit ->
+ ActiveHabitCard(
+ habit = habit,
+ onClick = { onHabitClick(habit.id) },
+ viewModel = viewModel
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun ActiveHabitCard(
+ habit: Habit,
+ onClick: () -> Unit,
+ viewModel: HabitViewModel
+) {
+ val weeklyProgress by viewModel.weeklyProgress(habit.id)
+ .collectAsState(initial = 0f)
+
+ Card(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onClick),
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Box(
+ modifier = Modifier
+ .size(44.dp)
+ .clip(CircleShape)
+ .background(MaterialTheme.colorScheme.surfaceVariant),
+ contentAlignment = Alignment.Center
+ ) {
+ // First letter of activity type
+ Text(
+ text = if (habit.activityType.isNotBlank()) habit.activityType.first().toString() else "•",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.primary
+ )
+ }
+
+ Spacer(modifier = Modifier.width(14.dp))
+
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = habit.displayName,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold
+ )
+ Spacer(modifier = Modifier.height(2.dp))
+ Text(
+ 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))
+ Text(
+ text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
+ )
+ }
+ }
+ }
+}
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 8cb5f28..98d93fa 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,6 +1,12 @@
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
@@ -8,250 +14,647 @@ 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.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
-import androidx.compose.material3.DropdownMenuItem
-import androidx.compose.material3.ExperimentalMaterial3Api
-import androidx.compose.material3.ExposedDropdownMenuBox
-import androidx.compose.material3.ExposedDropdownMenuDefaults
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
-import androidx.compose.material3.Switch
import androidx.compose.material3.Text
-import androidx.compose.material3.TopAppBar
-import androidx.compose.material3.TopAppBarDefaults
+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.data.model.HabitCategory
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.
- * When [existingHabit] is provided the form is pre-filled for editing.
+ *
+ * - 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.
*/
-@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEditHabitScreen(
viewModel: HabitViewModel,
existingHabit: Habit? = null,
onNavigateBack: () -> Unit
) {
+ val context = LocalContext.current
val isEditing = existingHabit != null
- var name by remember { mutableStateOf(existingHabit?.name ?: "") }
- var selectedCategory by remember {
- mutableStateOf(existingHabit?.category ?: HabitCategory.HEALTH)
- }
- var targetFrequency by remember {
+ // 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 remember { mutableStateOf(existingHabit?.reminderEnabled ?: true) }
- var reminderHour by remember { mutableIntStateOf(existingHabit?.reminderHour ?: 9) }
- var reminderMinute by remember { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) }
+ var reminderEnabled by rememberSaveable { mutableStateOf(existingHabit?.reminderEnabled ?: true) }
+ var reminderHour by rememberSaveable { mutableIntStateOf(existingHabit?.reminderHour ?: 9) }
+ var reminderMinute by rememberSaveable { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) }
- var nameError by remember { mutableStateOf(false) }
+ var nameError by rememberSaveable { mutableStateOf(false) }
+ var showActivityDialog by rememberSaveable { mutableStateOf(false) }
+ var showAddTypeDialog by rememberSaveable { mutableStateOf(false) }
+ var showTimePicker by rememberSaveable { mutableStateOf(false) }
- Scaffold(
- topBar = {
- TopAppBar(
- title = {
+ // ── Activity type picker dialog ─────────────────────────
+ if (showActivityDialog) {
+ AlertDialog(
+ onDismissRequest = { showActivityDialog = false },
+ title = { Text("Select Activity Type") },
+ text = {
+ if (activityTypes.isEmpty()) {
Text(
- if (isEditing) "Edit Habit" else "New Habit",
- fontWeight = FontWeight.Bold
+ "No activity types yet.\nTap the + button to create one.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
)
- },
- navigationIcon = {
- IconButton(onClick = onNavigateBack) {
- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
+ } 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
+ )
+ }
}
- },
- colors = TopAppBarDefaults.topAppBarColors(
- containerColor = MaterialTheme.colorScheme.primary,
- titleContentColor = MaterialTheme.colorScheme.onPrimary,
- navigationIconContentColor = MaterialTheme.colorScheme.onPrimary
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = { showActivityDialog = false }) { Text("Close") }
+ }
+ )
+ }
+
+ // ── Add new activity type dialog ────────────────────────
+ if (showAddTypeDialog) {
+ var newTypeName by remember { mutableStateOf("") }
+ var typeError by remember { mutableStateOf(false) }
+ AlertDialog(
+ onDismissRequest = { showAddTypeDialog = false },
+ title = { Text("New Activity Type") },
+ text = {
+ Column {
+ OutlinedTextField(
+ value = newTypeName,
+ onValueChange = { newTypeName = it; typeError = false },
+ label = { Text("Type name") },
+ placeholder = { Text("e.g. Gym, Running, Yoga") },
+ singleLine = true,
+ isError = typeError,
+ modifier = Modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(12.dp)
+ )
+ if (typeError) {
+ Text(
+ "Name is empty or already exists",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = {
+ if (newTypeName.isBlank()) {
+ typeError = true
+ } else {
+ viewModel.addActivityType(newTypeName) { success ->
+ if (success) {
+ selectedActivityName = HabitViewModel.toTitleCase(newTypeName.trim())
+ nameError = false
+ showAddTypeDialog = false
+ } else {
+ typeError = true
+ }
+ }
+ }
+ }) { Text("Add") }
+ },
+ dismissButton = {
+ TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") }
+ }
+ )
+ }
+
+ // ── Time picker dialog (clock dial) ─────────────────────
+ if (showTimePicker) {
+ var tempHour by remember { mutableIntStateOf(reminderHour) }
+ var tempMinute by remember { mutableIntStateOf(reminderMinute) }
+ var pickingHour by remember { mutableStateOf(true) }
+
+ AlertDialog(
+ onDismissRequest = { showTimePicker = false },
+ title = {
+ Text(
+ if (pickingHour) "Select Hour" else "Select Minute",
+ textAlign = TextAlign.Center,
+ modifier = Modifier.fillMaxWidth()
)
- )
- }
- ) { padding ->
+ },
+ text = {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ 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()
+ )
+ 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()
+ )
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = {
+ reminderHour = tempHour
+ reminderMinute = tempMinute
+ showTimePicker = false
+ }) { Text("OK") }
+ },
+ dismissButton = {
+ TextButton(onClick = { showTimePicker = false }) { Text("Cancel") }
+ }
+ )
+ }
+
+ // ── Screen layout ───────────────────────────────────────
+ Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
- .padding(20.dp)
- .verticalScroll(rememberScrollState()),
- verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- // Name
- OutlinedTextField(
- value = name,
- onValueChange = {
- name = it
- nameError = false
- },
- label = { Text("Habit Name") },
- placeholder = { Text("e.g. Drink 8 glasses of water") },
- isError = nameError,
- supportingText = if (nameError) {
- { Text("Name cannot be empty") }
- } else null,
- singleLine = true,
- modifier = Modifier.fillMaxWidth(),
- shape = RoundedCornerShape(12.dp)
- )
-
- // Category dropdown
- var categoryExpanded by remember { mutableStateOf(false) }
- ExposedDropdownMenuBox(
- expanded = categoryExpanded,
- onExpandedChange = { categoryExpanded = !categoryExpanded }
+ // Header bar
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(MaterialTheme.colorScheme.primary)
+ .padding(horizontal = 16.dp, vertical = 16.dp)
) {
- OutlinedTextField(
- value = selectedCategory.displayName,
- onValueChange = {},
- readOnly = true,
- label = { Text("Category") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) },
- modifier = Modifier
- .fillMaxWidth()
- .menuAnchor(),
- shape = RoundedCornerShape(12.dp)
- )
- ExposedDropdownMenu(
- expanded = categoryExpanded,
- onDismissRequest = { categoryExpanded = false }
- ) {
- HabitCategory.entries.forEach { cat ->
- DropdownMenuItem(
- text = { Text(cat.displayName) },
- onClick = {
- selectedCategory = cat
- categoryExpanded = false
- }
- )
- }
- }
- }
-
- // 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)
- )
-
- // Reminder toggle
- Row(
- modifier = Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.SpaceBetween
- ) {
- Text("Daily Reminder", style = MaterialTheme.typography.bodyLarge)
- Switch(
- checked = reminderEnabled,
- onCheckedChange = { reminderEnabled = it }
- )
- }
-
- if (reminderEnabled) {
- // Simple hour/minute pickers as text fields
Row(
modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
+ verticalAlignment = Alignment.CenterVertically
) {
- OutlinedTextField(
- value = reminderHour.toString().padStart(2, '0'),
- onValueChange = {
- val h = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0
- reminderHour = h.coerceIn(0, 23)
- },
- label = { Text("Hour (0-23)") },
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- singleLine = true,
- modifier = Modifier.weight(1f),
- shape = RoundedCornerShape(12.dp)
+ Text(
+ text = "←",
+ modifier = Modifier
+ .clickable(onClick = onNavigateBack)
+ .padding(end = 16.dp),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
)
- OutlinedTextField(
- value = reminderMinute.toString().padStart(2, '0'),
- onValueChange = {
- val m = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0
- reminderMinute = m.coerceIn(0, 59)
- },
- label = { Text("Minute (0-59)") },
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- singleLine = true,
- modifier = Modifier.weight(1f),
- shape = RoundedCornerShape(12.dp)
+ Text(
+ text = if (isEditing) "Edit Habit" else "New Habit",
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
)
}
}
- Spacer(modifier = Modifier.height(8.dp))
-
- // Save button
- Button(
- onClick = {
- if (name.isBlank()) {
- nameError = true
- return@Button
+ Column(
+ 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
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Card(
+ modifier = Modifier
+ .weight(1f)
+ .clickable { showActivityDialog = true },
+ shape = RoundedCornerShape(12.dp),
+ elevation = CardDefaults.cardElevation(1.dp),
+ colors = if (nameError) CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.errorContainer
+ ) else CardDefaults.cardColors()
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = if (selectedActivityName.isBlank()) "Tap to select…"
+ else selectedActivityName,
+ style = MaterialTheme.typography.bodyLarge,
+ color = if (selectedActivityName.isBlank())
+ MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
+ else MaterialTheme.colorScheme.onSurface
+ )
+ Text(
+ text = "▼",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
}
- val freq = targetFrequency.toIntOrNull() ?: 7
- if (isEditing && existingHabit != null) {
- viewModel.updateHabit(
- existingHabit.copy(
- name = name.trim(),
- category = selectedCategory,
+ // "+" 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)
+ }
+ }
+ if (nameError) {
+ Text(
+ text = "Please select an activity type",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ modifier = Modifier.padding(start = 4.dp)
+ )
+ }
+
+ // ── Details text field ──────────────────────────
+ 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)
+ )
+
+ // Live preview
+ if (selectedActivityName.isNotBlank()) {
+ val previewName = if (details.isBlank())
+ HabitViewModel.toTitleCase(selectedActivityName.trim())
+ else
+ HabitViewModel.toTitleCase(selectedActivityName.trim()) +
+ "(" + HabitViewModel.toTitleCase(details.trim()) + ")"
+ Text(
+ text = "Will display as: $previewName",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.padding(start = 4.dp)
+ )
+ }
+
+ // ── 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)
+ )
+
+ // ── 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)
+ ) {
+ Text(if (reminderEnabled) "ON" else "OFF")
+ }
+ }
+
+ if (reminderEnabled) {
+ // ── Reminder time — clock dial button ───────
+ Card(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { showTimePicker = true },
+ shape = RoundedCornerShape(12.dp),
+ elevation = CardDefaults.cardElevation(1.dp)
+ ) {
+ Row(
+ 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')}",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.primary
+ )
+ }
+ }
+ }
+
+ Spacer(modifier = Modifier.height(8.dp))
+
+ // ── Save button ─────────────────────────────────
+ Button(
+ onClick = {
+ if (selectedActivityName.isBlank()) {
+ nameError = true
+ return@Button
+ }
+ val freq = targetFrequency.toIntOrNull() ?: 7
+
+ if (isEditing && existingHabit != null) {
+ viewModel.updateHabit(
+ existingHabit.copy(
+ name = selectedActivityName.trim(),
+ details = details.trim(),
+ activityType = selectedActivityName.trim(),
+ targetFrequency = freq,
+ reminderEnabled = reminderEnabled,
+ reminderHour = reminderHour,
+ reminderMinute = reminderMinute
+ )
+ )
+ Log.i("AddEditHabitScreen", "User updated habit: name='${selectedActivityName.trim()}'")
+ onNavigateBack()
+ } else {
+ viewModel.addHabit(
+ name = selectedActivityName.trim(),
+ details = details.trim(),
+ activityType = selectedActivityName.trim(),
targetFrequency = freq,
reminderEnabled = reminderEnabled,
reminderHour = reminderHour,
- reminderMinute = reminderMinute
+ 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()
+ }
+ }
)
- )
- } else {
- viewModel.addHabit(
- name = name.trim(),
- category = selectedCategory,
- targetFrequency = freq,
- reminderEnabled = reminderEnabled,
- reminderHour = reminderHour,
- reminderMinute = reminderMinute
- )
- }
- onNavigateBack()
- },
- modifier = Modifier
- .fillMaxWidth()
- .height(52.dp),
- shape = RoundedCornerShape(14.dp)
- ) {
- Text(
- if (isEditing) "Update Habit" else "Create Habit",
- style = MaterialTheme.typography.titleMedium,
- fontWeight = FontWeight.Bold
- )
+ }
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(52.dp),
+ shape = RoundedCornerShape(14.dp)
+ ) {
+ Text(
+ if (isEditing) "Update Habit" else "Create Habit",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ }
}
}
}
}
+// ─────────────────────────────────────────────────────────────
+// 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
new file mode 100644
index 0000000..8a9376d
--- /dev/null
+++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/AllActivitiesScreen.kt
@@ -0,0 +1,220 @@
+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
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.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.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.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+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
+
+/**
+ * Shows ALL activities — both active and past/completed.
+ * Read-only listing; tapping a card navigates to its detail screen.
+ */
+@Composable
+fun AllActivitiesScreen(
+ viewModel: HabitViewModel,
+ onNavigateBack: () -> Unit,
+ onHabitClick: (Int) -> Unit
+) {
+ val habits by viewModel.allHabits.collectAsState()
+ val todayLogs by viewModel.todayLogs.collectAsState()
+ val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
+
+ Scaffold { padding ->
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding)
+ ) {
+ // Header
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(MaterialTheme.colorScheme.primary)
+ .padding(horizontal = 16.dp, vertical = 16.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = "←",
+ modifier = Modifier
+ .clickable(onClick = onNavigateBack)
+ .padding(end = 16.dp),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = "All Activities",
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ }
+ }
+
+ if (habits.isEmpty()) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(32.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ 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),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ items(habits, key = { it.id }) { habit ->
+ AllActivityCard(
+ habit = habit,
+ isCompletedToday = todayCompletedIds.contains(habit.id),
+ onClick = { onHabitClick(habit.id) },
+ viewModel = viewModel
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun AllActivityCard(
+ habit: Habit,
+ isCompletedToday: Boolean,
+ onClick: () -> Unit,
+ viewModel: HabitViewModel
+) {
+ val weeklyProgress by viewModel.weeklyProgress(habit.id)
+ .collectAsState(initial = 0f)
+
+ Card(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onClick),
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
+ colors = CardDefaults.cardColors(
+ containerColor = when {
+ !habit.isActive -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
+ isCompletedToday -> MaterialTheme.colorScheme.primaryContainer
+ else -> MaterialTheme.colorScheme.surface
+ }
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ // Status circle
+ Box(
+ modifier = Modifier
+ .size(44.dp)
+ .clip(CircleShape)
+ .background(
+ when {
+ !habit.isActive -> MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)
+ isCompletedToday -> MaterialTheme.colorScheme.primary
+ else -> MaterialTheme.colorScheme.surfaceVariant
+ }
+ ),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = when {
+ !habit.isActive -> "—"
+ isCompletedToday -> "✓"
+ else -> ""
+ },
+ color = if (isCompletedToday) 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)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ text = habit.displayName,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold
+ )
+ if (!habit.isActive) {
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(
+ text = "Retired",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ Spacer(modifier = Modifier.height(2.dp))
+ Text(
+ 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))
+ Text(
+ text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
+ )
+ }
+ }
+ }
+}
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 fa887f4..89dbf6a 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,6 +1,9 @@
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
@@ -9,6 +12,7 @@ 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
@@ -18,46 +22,37 @@ 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.material.icons.Icons
-import androidx.compose.material.icons.automirrored.filled.ArrowBack
-import androidx.compose.material.icons.filled.Delete
-import androidx.compose.material.icons.filled.Edit
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.ExperimentalMaterial3Api
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
-import androidx.compose.material3.TopAppBar
-import androidx.compose.material3.TopAppBarDefaults
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.data.model.HabitCategory
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
-@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HabitDetailScreen(
habitId: Int,
@@ -81,9 +76,10 @@ fun HabitDetailScreen(
AlertDialog(
onDismissRequest = { showDeleteDialog = false },
title = { Text("Delete Habit") },
- text = { Text("Are you sure you want to delete \"${habit!!.name}\"? All associated data will be lost.") },
+ text = { Text("Are you sure you want to delete \"${habit!!.displayName}\"? All associated data will be lost.") },
confirmButton = {
TextButton(onClick = {
+ Log.i("HabitDetail", "User confirmed DELETE for habit '${habit!!.displayName}' (id=${habit!!.id})")
viewModel.deleteHabit(habit!!)
showDeleteDialog = false
onNavigateBack()
@@ -92,231 +88,320 @@ fun HabitDetailScreen(
}
},
dismissButton = {
- TextButton(onClick = { showDeleteDialog = false }) {
- Text("Cancel")
- }
+ TextButton(onClick = { showDeleteDialog = false }) { Text("Cancel") }
}
)
}
- Scaffold(
- topBar = {
- TopAppBar(
- title = { Text(habit?.name ?: "Habit Detail", fontWeight = FontWeight.Bold) },
- navigationIcon = {
- IconButton(onClick = onNavigateBack) {
- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
- }
- },
- actions = {
- IconButton(onClick = { onEditHabit(habitId) }) {
- Icon(Icons.Default.Edit, contentDescription = "Edit")
- }
- IconButton(onClick = { showDeleteDialog = true }) {
- Icon(Icons.Default.Delete, contentDescription = "Delete")
- }
- },
- colors = TopAppBarDefaults.topAppBarColors(
- containerColor = MaterialTheme.colorScheme.primary,
- titleContentColor = MaterialTheme.colorScheme.onPrimary,
- navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
- actionIconContentColor = MaterialTheme.colorScheme.onPrimary
- )
- )
- }
- ) { padding ->
- if (habit == null) {
- Box(
- modifier = Modifier.fillMaxSize().padding(padding),
- contentAlignment = Alignment.Center
- ) {
- Text("Loading…")
- }
- return@Scaffold
- }
-
- val h = habit!!
- val dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
-
+ Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
- .verticalScroll(rememberScrollState())
- .padding(20.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- // Info card
- Card(
- shape = RoundedCornerShape(16.dp),
- elevation = CardDefaults.cardElevation(2.dp),
- modifier = Modifier.fillMaxWidth()
- ) {
- Column(modifier = Modifier.padding(16.dp)) {
- Text(
- text = categoryEmoji(h.category) + " " + h.category.displayName,
- style = MaterialTheme.typography.labelLarge,
- color = MaterialTheme.colorScheme.primary
- )
- Spacer(modifier = Modifier.height(4.dp))
- Text(
- text = "Started: ${dateFormat.format(Date(h.startDate))}",
- style = MaterialTheme.typography.bodyMedium
- )
- Text(
- text = "Target: ${h.targetFrequency}x per week",
- style = MaterialTheme.typography.bodyMedium
- )
- if (h.reminderEnabled) {
- Text(
- text = "Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${
- h.reminderMinute.toString().padStart(2, '0')
- }",
- style = MaterialTheme.typography.bodyMedium
- )
- }
- }
- }
-
- // Mark today button
- Button(
- onClick = { viewModel.toggleTodayLog(habitId) },
+ // Custom header bar (replaces TopAppBar which uses material.icons)
+ Box(
modifier = Modifier
.fillMaxWidth()
- .height(52.dp),
- shape = RoundedCornerShape(14.dp),
- colors = if (isCompletedToday) ButtonDefaults.buttonColors(
- containerColor = MaterialTheme.colorScheme.secondaryContainer,
- contentColor = MaterialTheme.colorScheme.onSecondaryContainer
- ) else ButtonDefaults.buttonColors()
+ .background(MaterialTheme.colorScheme.primary)
+ .padding(horizontal = 16.dp, vertical = 16.dp)
) {
- Text(
- if (isCompletedToday) "✅ Completed Today — Tap to Undo"
- else "Mark Today as Done",
- fontWeight = FontWeight.Bold
- )
- }
-
- // Streak cards
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- StatCard(
- title = "🔥 Current Streak",
- value = "$currentStreak day${if (currentStreak != 1) "s" else ""}",
- modifier = Modifier.weight(1f)
- )
- StatCard(
- title = "🏆 Longest Streak",
- value = "$longestStreak day${if (longestStreak != 1) "s" else ""}",
- modifier = Modifier.weight(1f)
- )
- }
-
- // Weekly progress
- Card(
- shape = RoundedCornerShape(16.dp),
- elevation = CardDefaults.cardElevation(2.dp),
- modifier = Modifier.fillMaxWidth()
- ) {
- Column(modifier = Modifier.padding(16.dp)) {
- Text(
- 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(
- text = "${(weeklyProgress * 100).toInt()}% of weekly goal",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant
- )
- }
- }
-
- // Last 14 days heatmap
- Text(
- text = "Last 14 Days",
- style = MaterialTheme.typography.titleMedium,
- fontWeight = FontWeight.SemiBold
- )
-
- val logDates = logs.filter { it.completed }.map { normaliseToDay(it.date) }.toSet()
- val today = todayStartMillis()
- val last14 = (0..13).map { today - it * 86_400_000L }.reversed()
-
- LazyRow(
- horizontalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- items(last14) { dayMillis ->
- val completed = logDates.contains(dayMillis)
- val dayFormat = SimpleDateFormat("dd", Locale.getDefault())
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Box(
- modifier = Modifier
- .size(36.dp)
- .clip(CircleShape)
- .background(
- if (completed) MaterialTheme.colorScheme.primary
- else MaterialTheme.colorScheme.surfaceVariant
- ),
- contentAlignment = Alignment.Center
- ) {
- Text(
- text = if (completed) "✓" else "",
- color = if (completed) MaterialTheme.colorScheme.onPrimary
- else MaterialTheme.colorScheme.onSurfaceVariant,
- style = MaterialTheme.typography.labelSmall
- )
- }
- Spacer(modifier = Modifier.height(2.dp))
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
Text(
- text = dayFormat.format(Date(dayMillis)),
- style = MaterialTheme.typography.labelSmall,
- textAlign = TextAlign.Center
+ text = "←",
+ modifier = Modifier
+ .clickable(onClick = onNavigateBack)
+ .padding(end = 12.dp),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = habit?.displayName ?: "Habit Detail",
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ }
+ Row {
+ Text(
+ text = "✏️",
+ modifier = Modifier
+ .clickable { onEditHabit(habitId) }
+ .padding(horizontal = 8.dp),
+ style = MaterialTheme.typography.titleLarge
+ )
+ Text(
+ text = "🗑️",
+ modifier = Modifier
+ .clickable { showDeleteDialog = true }
+ .padding(horizontal = 8.dp),
+ style = MaterialTheme.typography.titleLarge
)
}
}
}
- // Total completions
- val totalCompletions = logs.count { it.completed }
- Card(
- shape = RoundedCornerShape(16.dp),
- elevation = CardDefaults.cardElevation(2.dp),
- modifier = Modifier.fillMaxWidth()
- ) {
- Row(
- modifier = Modifier.padding(16.dp),
- verticalAlignment = Alignment.CenterVertically
+ if (habit == null) {
+ Box(
+ modifier = Modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
) {
- Text("📊", style = MaterialTheme.typography.headlineMedium)
- Spacer(modifier = Modifier.width(12.dp))
- Column {
+ Text("Loading…")
+ }
+ return@Scaffold
+ }
+
+ val h = habit!!
+ val dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ // Info card
+ Card(
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(2.dp),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Column(modifier = Modifier.padding(16.dp)) {
Text(
- "Total Completions",
- style = MaterialTheme.typography.titleSmall,
- fontWeight = FontWeight.SemiBold
+ text = h.activityType,
+ style = MaterialTheme.typography.labelLarge,
+ color = MaterialTheme.colorScheme.primary
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ Text(
+ text = "Started: ${dateFormat.format(Date(h.startDate))}",
+ style = MaterialTheme.typography.bodyMedium
)
Text(
- "$totalCompletions time${if (totalCompletions != 1) "s" else ""}",
- style = MaterialTheme.typography.bodyMedium,
+ text = "Target: ${h.targetFrequency}x per week",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ if (h.reminderEnabled) {
+ Text(
+ text = "Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${h.reminderMinute.toString().padStart(2, '0')}",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ }
+ }
+ }
+
+ // Swipe to mark today as complete (or undo)
+ SwipeToCompleteBar(
+ isCompletedToday = isCompletedToday,
+ onSwipeComplete = {
+ Log.i("HabitDetail", "Swipe-to-complete triggered for habit '${h.displayName}' (id=${h.id}), isUndo=${isCompletedToday}")
+ viewModel.toggleTodayLog(habitId)
+ }
+ )
+
+ // Streak cards
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ StatCard(
+ title = "🔥 Current Streak",
+ value = "$currentStreak day${if (currentStreak != 1) "s" else ""}",
+ modifier = Modifier.weight(1f)
+ )
+ StatCard(
+ title = "🏆 Longest Streak",
+ value = "$longestStreak day${if (longestStreak != 1) "s" else ""}",
+ modifier = Modifier.weight(1f)
+ )
+ }
+
+ // Weekly progress
+ Card(
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(2.dp),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Column(modifier = Modifier.padding(16.dp)) {
+ Text(
+ 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(
+ text = "${(weeklyProgress * 100).toInt()}% of weekly goal",
+ style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
- }
- Spacer(modifier = Modifier.height(16.dp))
+ // Last 14 days heatmap
+ Text(
+ text = "Last 14 Days",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold
+ )
+
+ val logDates = logs.filter { it.completed }.map { normaliseToDay(it.date) }.toSet()
+ val today = todayStartMillis()
+ val last14 = (0..13).map { today - it * 86_400_000L }.reversed()
+
+ LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ items(last14) { dayMillis ->
+ val completed = logDates.contains(dayMillis)
+ val dayFormat = SimpleDateFormat("dd", Locale.getDefault())
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Box(
+ modifier = Modifier
+ .size(36.dp)
+ .clip(CircleShape)
+ .background(
+ if (completed) MaterialTheme.colorScheme.primary
+ else MaterialTheme.colorScheme.surfaceVariant
+ ),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = if (completed) "✓" else "",
+ color = if (completed) MaterialTheme.colorScheme.onPrimary
+ else MaterialTheme.colorScheme.onSurfaceVariant,
+ style = MaterialTheme.typography.labelSmall
+ )
+ }
+ Spacer(modifier = Modifier.height(2.dp))
+ Text(
+ text = dayFormat.format(Date(dayMillis)),
+ style = MaterialTheme.typography.labelSmall,
+ textAlign = TextAlign.Center
+ )
+ }
+ }
+ }
+
+ // Total completions
+ val totalCompletions = logs.count { it.completed }
+ Card(
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(2.dp),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ 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(
+ "$totalCompletions time${if (totalCompletions != 1) "s" else ""}",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ }
+
+ Spacer(modifier = Modifier.height(16.dp))
+ }
+ }
+ }
+}
+
+/**
+ * Swipe-to-complete bar for the detail screen.
+ * User must swipe right past a threshold to toggle completion.
+ */
+@Composable
+private fun SwipeToCompleteBar(
+ isCompletedToday: Boolean,
+ onSwipeComplete: () -> Unit
+) {
+ val swipeThreshold = 200f
+ var offsetX by remember { mutableFloatStateOf(0f) }
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(56.dp)
+ .clip(RoundedCornerShape(14.dp))
+ ) {
+ // Background
+ Box(
+ modifier = Modifier
+ .matchParentSize()
+ .background(
+ if (isCompletedToday) MaterialTheme.colorScheme.secondaryContainer
+ else MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
+ ),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = if (isCompletedToday) "← Swipe → to Undo"
+ else "← Swipe → to Complete Today",
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.Bold,
+ color = if (isCompletedToday) MaterialTheme.colorScheme.onSecondaryContainer
+ else MaterialTheme.colorScheme.primary
+ )
+ }
+
+ // Draggable thumb
+ Box(
+ modifier = Modifier
+ .size(width = 80.dp, height = 56.dp)
+ .offset { IntOffset(offsetX.roundToInt(), 0) }
+ .clip(RoundedCornerShape(14.dp))
+ .background(
+ if (isCompletedToday) MaterialTheme.colorScheme.secondary
+ else MaterialTheme.colorScheme.primary
+ )
+ .pointerInput(isCompletedToday) {
+ detectHorizontalDragGestures(
+ onDragEnd = {
+ if (offsetX > swipeThreshold) {
+ Log.d("SwipeGesture", "Detail swipe threshold reached, toggling completion")
+ onSwipeComplete()
+ }
+ offsetX = 0f
+ },
+ onDragCancel = { offsetX = 0f },
+ onHorizontalDrag = { _, dragAmount ->
+ offsetX = (offsetX + dragAmount).coerceIn(0f, swipeThreshold + 50f)
+ }
+ )
+ },
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = if (isCompletedToday) "✅" else "→",
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
}
}
}
@@ -353,13 +438,6 @@ private fun StatCard(title: String, value: String, modifier: Modifier = Modifier
}
}
-private fun categoryEmoji(category: HabitCategory): String = when (category) {
- HabitCategory.HEALTH -> "❤️"
- HabitCategory.STUDY -> "📚"
- HabitCategory.FITNESS -> "💪"
- HabitCategory.WELLBEING -> "🧘"
-}
-
private fun normaliseToDay(millis: Long): Long {
val cal = Calendar.getInstance()
cal.timeInMillis = millis
@@ -378,4 +456,3 @@ private fun todayStartMillis(): Long {
cal.set(Calendar.MILLISECOND, 0)
return cal.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 c8698cb..704b24d 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,8 +1,9 @@
package com.example.madwellbeingapp.ui.screens
-import androidx.compose.animation.animateContentSize
+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
@@ -11,6 +12,7 @@ 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
@@ -18,14 +20,9 @@ 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.material.icons.Icons
-import androidx.compose.material.icons.filled.Add
-import androidx.compose.material.icons.filled.Check
+import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
-import androidx.compose.material3.FloatingActionButton
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
@@ -33,56 +30,71 @@ 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.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
import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit
-import com.example.madwellbeingapp.data.model.HabitCategory
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
+import kotlin.math.roundToInt
+/**
+ * Manage Activities screen — the user can add a new activity or
+ * swipe to mark an existing active habit as done.
+ */
@Composable
fun HomeScreen(
viewModel: HabitViewModel,
onAddHabit: () -> Unit,
- onHabitClick: (Int) -> Unit
+ onHabitClick: (Int) -> Unit,
+ onNavigateBack: () -> Unit
) {
val habits by viewModel.allHabits.collectAsState()
val todayLogs by viewModel.todayLogs.collectAsState()
val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
- Scaffold(
- floatingActionButton = {
- FloatingActionButton(
- onClick = onAddHabit,
- containerColor = MaterialTheme.colorScheme.primary
- ) {
- Icon(Icons.Default.Add, contentDescription = "Add Habit")
- }
- }
- ) { padding ->
+ // Only show active habits on this management screen
+ val activeHabits = habits.filter { it.isActive }
+
+ Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
- // Header
+ // Header with back button
Column(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 20.dp, vertical = 24.dp)
) {
- Text(
- text = "Smart Habit Companion",
- style = MaterialTheme.typography.headlineSmall,
- color = MaterialTheme.colorScheme.onPrimary,
- fontWeight = FontWeight.Bold
- )
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ text = "←",
+ modifier = Modifier
+ .clickable(onClick = onNavigateBack)
+ .padding(end = 16.dp),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = "Manage Activities",
+ style = MaterialTheme.typography.headlineSmall,
+ color = MaterialTheme.colorScheme.onPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ }
Spacer(modifier = Modifier.height(4.dp))
val dateFormat = SimpleDateFormat("EEEE, MMM d", Locale.getDefault())
Text(
@@ -92,8 +104,8 @@ fun HomeScreen(
)
Spacer(modifier = Modifier.height(12.dp))
// Quick summary
- val completedToday = todayCompletedIds.size
- val total = habits.size
+ val completedToday = activeHabits.count { todayCompletedIds.contains(it.id) }
+ val total = activeHabits.size
Text(
text = "$completedToday / $total habits completed today",
style = MaterialTheme.typography.bodyLarge,
@@ -114,10 +126,11 @@ fun HomeScreen(
}
}
- if (habits.isEmpty()) {
+ if (activeHabits.isEmpty()) {
Box(
modifier = Modifier
.fillMaxSize()
+ .weight(1f)
.padding(32.dp),
contentAlignment = Alignment.Center
) {
@@ -129,7 +142,7 @@ fun HomeScreen(
)
Spacer(modifier = Modifier.height(8.dp))
Text(
- text = "Tap + to create your first habit",
+ text = "Tap the button below to create your first habit",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
@@ -138,127 +151,193 @@ fun HomeScreen(
} else {
LazyColumn(
modifier = Modifier
- .fillMaxSize()
+ .weight(1f)
+ .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
- items(habits, key = { it.id }) { habit ->
- HabitCard(
+ items(activeHabits, key = { it.id }) { habit ->
+ SwipeToCompleteHabitCard(
habit = habit,
isCompletedToday = todayCompletedIds.contains(habit.id),
- onToggle = { viewModel.toggleTodayLog(habit.id) },
+ onSwipeComplete = { viewModel.toggleTodayLog(habit.id) },
onClick = { onHabitClick(habit.id) },
viewModel = viewModel
)
}
}
}
+
+ // Add habit button at the bottom
+ Button(
+ onClick = onAddHabit,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 12.dp)
+ .height(52.dp),
+ shape = RoundedCornerShape(14.dp)
+ ) {
+ Text(
+ text = "+ Add New Habit",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ }
}
}
}
+/**
+ * A habit card that requires a horizontal swipe gesture to mark as complete.
+ * The user must swipe right past a threshold to toggle completion.
+ * This prevents accidental taps from marking habits complete.
+ */
@Composable
-private fun HabitCard(
+private fun SwipeToCompleteHabitCard(
habit: Habit,
isCompletedToday: Boolean,
- onToggle: () -> Unit,
+ onSwipeComplete: () -> Unit,
onClick: () -> Unit,
viewModel: HabitViewModel
) {
val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f)
- Card(
+ val swipeThreshold = 150f
+ var offsetX by remember { mutableFloatStateOf(0f) }
+
+ Box(
modifier = Modifier
.fillMaxWidth()
- .animateContentSize()
- .clickable(onClick = onClick),
- shape = RoundedCornerShape(16.dp),
- elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
- colors = CardDefaults.cardColors(
- containerColor = if (isCompletedToday)
- MaterialTheme.colorScheme.primaryContainer
- else MaterialTheme.colorScheme.surface
- )
+ .clip(RoundedCornerShape(16.dp))
) {
- Row(
+ // Background revealed on swipe
+ Box(
+ modifier = Modifier
+ .matchParentSize()
+ .background(
+ if (isCompletedToday) MaterialTheme.colorScheme.error.copy(alpha = 0.2f)
+ else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
+ ),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ Text(
+ text = if (isCompletedToday) " ← Undo" else " ← Swipe to Complete →",
+ modifier = Modifier.padding(start = 16.dp),
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.Bold,
+ color = if (isCompletedToday) MaterialTheme.colorScheme.error
+ else MaterialTheme.colorScheme.primary
+ )
+ }
+
+ // Foreground card that slides
+ Card(
modifier = Modifier
.fillMaxWidth()
- .padding(16.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- // Check button
- IconButton(
- onClick = onToggle,
- modifier = Modifier
- .size(44.dp)
- .clip(CircleShape)
- .background(
- if (isCompletedToday)
- MaterialTheme.colorScheme.primary
- else
- MaterialTheme.colorScheme.surfaceVariant
+ .offset { IntOffset(offsetX.roundToInt(), 0) }
+ .pointerInput(isCompletedToday) {
+ detectHorizontalDragGestures(
+ onDragEnd = {
+ if (offsetX > swipeThreshold) {
+ Log.d("SwipeGesture", "Swipe threshold reached for habit '${habit.displayName}' (id=${habit.id}), toggling completion")
+ onSwipeComplete()
+ }
+ offsetX = 0f
+ },
+ onDragCancel = {
+ offsetX = 0f
+ },
+ onHorizontalDrag = { _, dragAmount ->
+ // Only allow rightward swipe (positive direction)
+ offsetX = (offsetX + dragAmount).coerceIn(0f, swipeThreshold + 50f)
+ }
)
+ }
+ .clickable(onClick = onClick),
+ shape = RoundedCornerShape(16.dp),
+ elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
+ colors = CardDefaults.cardColors(
+ containerColor = if (isCompletedToday)
+ MaterialTheme.colorScheme.primaryContainer
+ else MaterialTheme.colorScheme.surface
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically
) {
- Icon(
- imageVector = Icons.Default.Check,
- contentDescription = if (isCompletedToday) "Completed" else "Mark complete",
- tint = if (isCompletedToday)
- MaterialTheme.colorScheme.onPrimary
- else
- MaterialTheme.colorScheme.onSurfaceVariant
- )
- }
-
- Spacer(modifier = Modifier.width(14.dp))
-
- Column(modifier = Modifier.weight(1f)) {
- Text(
- text = habit.name,
- style = MaterialTheme.typography.titleMedium,
- fontWeight = FontWeight.SemiBold
- )
- Spacer(modifier = Modifier.height(2.dp))
- Text(
- text = categoryEmoji(habit.category) + " " + habit.category.displayName +
- " • ${habit.targetFrequency}x/week",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant
- )
- Spacer(modifier = Modifier.height(8.dp))
- // Weekly progress bar
- LinearProgressIndicator(
- progress = { weeklyProgress },
+ // Status indicator circle
+ Box(
modifier = Modifier
- .fillMaxWidth()
- .height(6.dp)
- .clip(RoundedCornerShape(3.dp)),
- color = categoryColor(habit.category),
- trackColor = MaterialTheme.colorScheme.surfaceVariant,
- )
- Spacer(modifier = Modifier.height(2.dp))
- Text(
- text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
- style = MaterialTheme.typography.labelSmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
- )
+ .size(44.dp)
+ .clip(CircleShape)
+ .background(
+ if (isCompletedToday)
+ MaterialTheme.colorScheme.primary
+ else
+ MaterialTheme.colorScheme.surfaceVariant
+ ),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = if (isCompletedToday) "✓" else "",
+ color = if (isCompletedToday)
+ 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(
+ text = habit.displayName,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold
+ )
+ Spacer(modifier = Modifier.height(2.dp))
+ Text(
+ text = habit.activityType + " • ${habit.targetFrequency}x/week",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ // Weekly progress bar
+ 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(
+ text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
+ )
+ if (!isCompletedToday) {
+ Text(
+ text = "Swipe → to complete",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
+ )
+ }
+ }
+ }
}
}
}
}
-
-private fun categoryEmoji(category: HabitCategory): String = when (category) {
- HabitCategory.HEALTH -> "❤️"
- HabitCategory.STUDY -> "📚"
- HabitCategory.FITNESS -> "💪"
- HabitCategory.WELLBEING -> "🧘"
-}
-
-@Composable
-private fun categoryColor(category: HabitCategory) = when (category) {
- HabitCategory.HEALTH -> MaterialTheme.colorScheme.error
- HabitCategory.STUDY -> MaterialTheme.colorScheme.tertiary
- HabitCategory.FITNESS -> MaterialTheme.colorScheme.primary
- HabitCategory.WELLBEING -> MaterialTheme.colorScheme.secondary
-}
-
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
new file mode 100644
index 0000000..f463f5c
--- /dev/null
+++ b/app/src/main/java/com/example/madwellbeingapp/ui/screens/LandingScreen.kt
@@ -0,0 +1,130 @@
+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.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+
+/**
+ * Landing screen — the first page the user sees.
+ * Contains 3 centred buttons:
+ * 1. All Activities (past + active)
+ * 2. Manage Activities (add / mark done)
+ * 3. Active Only (still to-do)
+ */
+@Composable
+fun LandingScreen(
+ onAllActivities: () -> Unit,
+ onManageActivities: () -> Unit,
+ onActiveOnly: () -> Unit
+) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(MaterialTheme.colorScheme.background)
+ .statusBarsPadding(),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 32.dp)
+ ) {
+ // App title
+ Text(
+ text = "Smart Habit\n& Wellbeing Companion",
+ style = MaterialTheme.typography.headlineMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.primary,
+ textAlign = TextAlign.Center
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ Text(
+ text = "Track your habits. Build your streaks.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ textAlign = TextAlign.Center
+ )
+
+ Spacer(modifier = Modifier.height(48.dp))
+
+ // Top button — All Activities
+ Button(
+ onClick = onAllActivities,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(56.dp),
+ shape = RoundedCornerShape(16.dp),
+ colors = ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.primary
+ )
+ ) {
+ Text(
+ text = "All Activities",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ }
+
+ Spacer(modifier = Modifier.height(16.dp))
+
+ // Middle button — Manage Activities
+ Button(
+ onClick = onManageActivities,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(56.dp),
+ shape = RoundedCornerShape(16.dp),
+ colors = ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.secondary
+ )
+ ) {
+ Text(
+ text = "Manage Activities",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ }
+
+ Spacer(modifier = Modifier.height(16.dp))
+
+ // Bottom button — Active Only
+ Button(
+ onClick = onActiveOnly,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(56.dp),
+ shape = RoundedCornerShape(16.dp),
+ colors = ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.tertiary
+ )
+ ) {
+ Text(
+ text = "Active Only",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ }
+ }
+ }
+}
+
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 d507972..d733289 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,12 +1,19 @@
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.HabitCategory
import com.example.madwellbeingapp.data.model.HabitLog
import com.example.madwellbeingapp.data.repository.HabitRepository
import com.example.madwellbeingapp.notification.HabitNotificationScheduler
@@ -16,6 +23,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
@@ -28,6 +36,70 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
private val repository: HabitRepository =
(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
+ * "GYM(LEGS)" → "Gym(Legs)" and "gym(legs)" → "Gym(Legs)".
+ */
+ fun toTitleCase(input: String): String {
+ if (input.isBlank()) return input
+ val sb = StringBuilder()
+ var capitalizeNext = true
+ for (ch in input) {
+ when {
+ ch == '(' || ch == ')' || ch == ' ' || ch == '-' -> {
+ sb.append(ch)
+ capitalizeNext = true
+ }
+ capitalizeNext -> {
+ sb.append(ch.uppercaseChar())
+ capitalizeNext = false
+ }
+ else -> {
+ sb.append(ch.lowercaseChar())
+ }
+ }
+ }
+ return sb.toString()
+ }
+ }
+
+ // ── Activity Types (user-created, stored in Room) ───────
+ val allActivityTypes: StateFlow> = repository.allActivityTypes
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
+
+ /**
+ * Adds a new activity type. [onResult] returns true on success, false if duplicate.
+ */
+ fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) {
+ viewModelScope.launch {
+ val formatted = toTitleCase(name.trim())
+ if (formatted.isBlank()) {
+ onResult(false)
+ return@launch
+ }
+ 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
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
@@ -46,9 +118,17 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
val todayLogs: StateFlow> = repository.getLogsForDate(todayStart)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
+ /**
+ * Active habits still to-do today.
+ */
+ val activeHabitsNotCompletedToday: StateFlow> =
+ combine(allHabits, todayLogs) { habits, logs ->
+ val completedIds = logs.filter { it.completed }.map { it.habitId }.toSet()
+ habits.filter { it.isActive && !completedIds.contains(it.id) }
+ }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
+
// ── Selected habit detail ───────────────────────────────
private val _selectedHabitId = MutableStateFlow(null)
- val selectedHabitId = _selectedHabitId.asStateFlow()
@OptIn(ExperimentalCoroutinesApi::class)
val selectedHabit: StateFlow = _selectedHabitId
@@ -84,37 +164,22 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
_longestStreak.value = 0
return@launch
}
-
- // Normalise dates to day-only & sort descending
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
-
- // Current streak: consecutive days ending today or yesterday
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
+ if (day == expected) { current++; expected -= 86_400_000L } else break
}
}
-
- // Longest streak
- var longest = 1
- var streak = 1
- val sorted = days.sortedDescending()
- for (i in 1 until sorted.size) {
- if (sorted[i] == sorted[i - 1] - 86_400_000L) {
- streak++
- if (streak > longest) longest = streak
- } else {
- streak = 1
- }
+ 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
}
-
_currentStreak.value = current
_longestStreak.value = longest
}
@@ -131,19 +196,39 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
}
}
+ // ── Duplicate check ─────────────────────────────────────
+ suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean {
+ val existing = repository.findDuplicate(name.trim(), details.trim())
+ return existing != null && existing.id != excludeId
+ }
+
// ── CRUD operations ─────────────────────────────────────
+
fun addHabit(
name: String,
- category: HabitCategory,
+ details: String = "",
+ activityType: String = "",
targetFrequency: Int,
reminderEnabled: Boolean = true,
reminderHour: Int = 9,
- reminderMinute: Int = 0
+ reminderMinute: Int = 0,
+ onResult: (Boolean) -> Unit = {}
) {
viewModelScope.launch {
+ val formattedName = toTitleCase(name.trim())
+ val formattedDetails = toTitleCase(details.trim())
+ val formattedType = toTitleCase(activityType.trim())
+
+ if (isDuplicate(formattedName, formattedDetails)) {
+ Log.w(TAG, "DUPLICATE BLOCKED: '$formattedName($formattedDetails)' already exists")
+ onResult(false)
+ return@launch
+ }
+
val habit = Habit(
- name = name,
- category = category,
+ name = formattedName,
+ details = formattedDetails,
+ activityType = formattedType,
startDate = System.currentTimeMillis(),
targetFrequency = targetFrequency,
reminderEnabled = reminderEnabled,
@@ -151,24 +236,32 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
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, name, reminderHour, reminderMinute
+ getApplication(), id, habit.displayName, reminderHour, reminderMinute
)
}
+ onResult(true)
}
}
fun updateHabit(habit: Habit) {
viewModelScope.launch {
- repository.updateHabit(habit)
- if (habit.reminderEnabled) {
+ val updated = habit.copy(
+ name = toTitleCase(habit.name.trim()),
+ details = toTitleCase(habit.details.trim()),
+ 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(), habit.id, habit.name,
- habit.reminderHour, habit.reminderMinute
+ getApplication(), updated.id, updated.displayName,
+ updated.reminderHour, updated.reminderMinute
)
} else {
- HabitNotificationScheduler.cancel(getApplication(), habit.id)
+ HabitNotificationScheduler.cancel(getApplication(), updated.id)
}
}
}
@@ -177,18 +270,22 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
HabitNotificationScheduler.cancel(getApplication(), habit.id)
repository.deleteHabit(habit)
+ Log.i(TAG, "HABIT DELETED: name='${habit.displayName}', id=${habit.id}")
}
}
// ── Daily logging ───────────────────────────────────────
fun toggleTodayLog(habitId: Int) {
viewModelScope.launch {
+ val existing = repository.getLogForDate(habitId, todayStart)
+ val habit = repository.getHabitByIdOnce(habitId)
repository.toggleLog(habitId, todayStart)
- // Refresh streaks if currently viewing this habit
- if (_selectedHabitId.value == habitId) {
- computeStreaks(habitId)
+ 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")
}
- // Celebrate streak milestones
+ if (_selectedHabitId.value == habitId) computeStreaks(habitId)
checkStreakCelebration(habitId)
}
}
@@ -197,52 +294,46 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) return
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
- val today = todayStart
- if (days.first() != today) return
- var streak = 0
- var expected = today
+ 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) {
- // Send a celebration notification
- sendCelebration(habitId, streak)
+ 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()
- val notification = androidx.core.app.NotificationCompat.Builder(ctx, HabitApp.CHANNEL_ID)
- .setSmallIcon(R.drawable.ic_launcher_foreground)
- .setContentTitle("🎉 Streak Milestone!")
- .setContentText("Amazing! You've hit a $streak-day streak on \"${habit.name}\"!")
- .setPriority(androidx.core.app.NotificationCompat.PRIORITY_HIGH)
- .setAutoCancel(true)
- .build()
-
- if (androidx.core.content.ContextCompat.checkSelfPermission(
- ctx, android.Manifest.permission.POST_NOTIFICATIONS
- ) == android.content.pm.PackageManager.PERMISSION_GRANTED
- ) {
- androidx.core.app.NotificationManagerCompat.from(ctx)
- .notify(habitId + 10_000, notification)
+ 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()
cal.timeInMillis = millis
- cal.set(Calendar.HOUR_OF_DAY, 0)
- cal.set(Calendar.MINUTE, 0)
- cal.set(Calendar.SECOND, 0)
- cal.set(Calendar.MILLISECOND, 0)
+ cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0)
+ cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
}
-
-
diff --git a/app/src/test/java/com/example/madwellbeingapp/ExampleUnitTest.kt b/app/src/test/java/com/example/madwellbeingapp/ExampleUnitTest.kt
new file mode 100644
index 0000000..83f713a
--- /dev/null
+++ b/app/src/test/java/com/example/madwellbeingapp/ExampleUnitTest.kt
@@ -0,0 +1,17 @@
+package com.example.madwellbeingapp
+
+import org.junit.Test
+
+import org.junit.Assert.*
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+class ExampleUnitTest {
+ @Test
+ fun addition_isCorrect() {
+ assertEquals(4, 2 + 2)
+ }
+}
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
index 0d56e2a..ab250af 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -23,3 +23,13 @@ kotlin.code.style=official
android.nonTransitiveRClass=true
# Allow KSP-generated Kotlin source sets with AGP built-in Kotlin
android.disallowKotlinSourceSets=false
+android.defaults.buildfeatures.resvalues=true
+android.sdk.defaultTargetSdkToCompileSdkIfUnset=false
+android.enableAppCompileTimeRClass=false
+android.usesSdkInManifest.disallowed=false
+android.uniquePackageNames=false
+android.dependency.useConstraints=true
+android.r8.strictFullModeForKeepRules=false
+android.r8.optimizedResourceShrinking=false
+android.builtInKotlin=false
+android.newDsl=false
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 594def3..5ddd6ac 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -1,17 +1,16 @@
[versions]
-agp = "8.13.2"
+agp = "9.0.1"
coreKtx = "1.10.1"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
lifecycleRuntimeKtx = "2.6.1"
activityCompose = "1.8.0"
-kotlin = "2.0.0"
+kotlin = "2.2.10"
composeBom = "2024.06.00"
-room = "2.6.1"
-navigationCompose = "2.7.7"
+room = "2.7.1"
lifecycleViewmodelCompose = "2.6.1"
-ksp = "2.0.0-1.0.21"
+ksp = "2.3.2"
coreKtxVersion = "1.17.0"
[libraries]
@@ -32,7 +31,6 @@ androidx-compose-material3 = { group = "androidx.compose.material3", name = "mat
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
-androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
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" }
@@ -40,4 +38,4 @@ core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtxV
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
+kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
\ No newline at end of file