Skip to content

Commit b163dcd

Browse files
author
mfelix
committed
Added summary page
1 parent 7dd9ecc commit b163dcd

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+588
-311
lines changed

app/src/main/java/com/mozzarelly/cbthelper/CBTActivity.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,19 @@ abstract class CBTActivity<V : CBTViewModel> : AppCompatActivity() {
2424
supportActionBar?.setDisplayShowHomeEnabled(true)
2525
}
2626

27+
/*
2728
val viewModelProvider: ViewModelProvider.NewInstanceFactory = object: ViewModelProvider.NewInstanceFactory() {
2829
@Suppress("UNCHECKED_CAST")
2930
override fun <T : ViewModel> create(modelClass: Class<T>): T {
3031
return modelClass.newInstance().also {
3132
(it as V).run {
32-
// applicationContext = [email protected]
33-
applicationContext = application.applicationContext
33+
// applicationContext = application.applicationContext
3434
setup()
3535
}
3636
}
3737
}
3838
}
39+
*/
3940

4041
open val onReturnFrom = mapOf<KClass<*>, (Int) -> Unit>(
4142

app/src/main/java/com/mozzarelly/cbthelper/CBTApplication.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ class CBTApplication : android.app.Application() {
1212
super.onCreate()
1313
AndroidThreeTen.init(this)
1414

15+
CBTDatabase.getDatabase(this)
16+
1517
val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE) ?: error("Can't get prefs.")
1618
val dark = prefs.getOrInit("dark"){
1719
(resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package com.mozzarelly.cbthelper
22

3-
import android.content.Context
43
import androidx.lifecycle.ViewModel
54

65
abstract class CBTViewModel: ViewModel(){
7-
lateinit var applicationContext: Context
86

97
}

app/src/main/java/com/mozzarelly/cbthelper/DB.kt

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ interface CogValidDao {
6969
@Query("SELECT * FROM cogvalid WHERE id = :id")
7070
fun getAsync(id: Int): LiveData<CogValid?>
7171

72+
@Query("SELECT * FROM cogvalid WHERE id = :id")
73+
fun getFlow(id: Int): Flow<CogValid?>
74+
7275
@Insert(entity = CogValid::class)
7376
suspend fun create(model: CogValid): Long
7477

@@ -89,6 +92,9 @@ interface RatRepDao {
8992
@Query("SELECT * FROM ratrep WHERE id = :id")
9093
fun getAsync(id: Int): LiveData<RatRep?>
9194

95+
@Query("SELECT * FROM ratrep WHERE id = :id")
96+
fun getFlow(id: Int): Flow<RatRep?>
97+
9298
@Insert(entity = RatRep::class)
9399
suspend fun create(model: RatRep): Long
94100

@@ -109,6 +115,9 @@ interface BehaviorDao {
109115
@Query("SELECT * FROM behavior WHERE id = :id")
110116
fun getAsync(id: Int): LiveData<Behavior?>
111117

118+
@Query("SELECT * FROM behavior WHERE id = :id")
119+
fun getFlow(id: Int): Flow<Behavior?>
120+
112121
@Insert(entity = Behavior::class)
113122
suspend fun create(model: Behavior): Long
114123

@@ -138,6 +147,10 @@ abstract class CBTDatabase : RoomDatabase() {
138147
}
139148
}
140149

150+
fun getDatabase(): CBTDatabase {
151+
return instance ?: error("Database not initialized! Pass a context first.")
152+
}
153+
141154
fun getEntryDao(context: Context): EntryDao = getDatabase(context).entryDao()
142155
fun getCogValidDao(context: Context): CogValidDao = getDatabase(context).cogValidDao()
143156
fun getRatRepDao(context: Context): RatRepDao = getDatabase(context).ratRepDao()
@@ -188,7 +201,7 @@ abstract class CBTDatabase : RoomDatabase() {
188201
override suspend fun doWork(): Result = coroutineScope {
189202
try {
190203
if (BuildConfig.DEBUG) {
191-
CBTDatabase.getDatabase(context).populateSampleData()
204+
getDatabase(context).populateSampleData()
192205
}
193206

194207
Result.success()
@@ -445,15 +458,11 @@ abstract class CBTDatabase : RoomDatabase() {
445458

446459
}
447460

448-
suspend fun Context.clean(addSampleData: Boolean = false){
449-
behaviorDao().deleteAll()
450-
ratRepDao().deleteAll()
451-
cogValidDao().deleteAll()
452-
entryDao().deleteAll()
461+
suspend fun clean(addSampleData: Boolean = false){
462+
clearAllTables()
453463

454464
if (addSampleData){
455-
val request = OneTimeWorkRequestBuilder<PopulateDatabaseWorker>().build()
456-
WorkManager.getInstance(this).enqueue(request)
465+
populateSampleData()
457466
}
458467
}
459468

app/src/main/java/com/mozzarelly/cbthelper/InterviewViewModel.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ abstract class InterviewViewModel : CBTViewModel(){
3232
abstract val complete: Boolean
3333
abstract val title: LiveData<String?>
3434

35-
val entryDao by lazy { CBTDatabase.getDatabase(applicationContext).entryDao() }
35+
val entryDao by lazy { CBTDatabase.getDatabase().entryDao() }
3636

3737
private val changingPageChannel = BroadcastChannel<Pair<Int, Int?>>(Channel.BUFFERED)
3838
val changingPage = changingPageChannel.asFlow()

app/src/main/java/com/mozzarelly/cbthelper/LiveDataUtils.kt

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ inline fun <T: Any?, R> LiveData<T?>.mapValue(crossinline convert: (T) -> R?): L
8686
*
8787
* @param convert A function to convert (A, B) to R.
8888
*/
89-
fun <A, B, R> Pair<LiveData<A>, LiveData<B>>.map(convert: (A?, B?) -> R): LiveData<R> = MediatorLiveData<R>().apply {
89+
fun <A: Any?, B: Any?, R> Pair<LiveData<A>, LiveData<B>>.map(convert: (A?, B?) -> R): LiveData<R> = MediatorLiveData<R>().apply {
9090
val update: Function0<Unit> = {
9191
val a = first.value
9292
val b = second.value
@@ -180,25 +180,25 @@ inline fun <reified A, reified B, reified C, R> Triple<LiveData<A>, LiveData<B>,
180180
}
181181
}
182182

183-
inline fun <reified A, reified B> observe(a: LiveData<A>, b: LiveData<B>, crossinline handler: (A?, B?) -> Unit) {
184-
a.observeForever {
183+
inline fun <reified A, reified B> LifecycleOwner.observe(a: LiveData<A>, b: LiveData<B>, crossinline handler: (A?, B?) -> Unit) {
184+
a.observe(this, Observer {
185185
handler(a.value, b.value)
186-
}
187-
b.observeForever {
186+
})
187+
b.observe(this, Observer {
188188
handler(a.value, b.value)
189-
}
189+
})
190190
}
191191

192-
inline fun <reified A, reified B, reified C> observe(a: LiveData<A>, b: LiveData<B>, c: LiveData<C>, crossinline handler: (A?, B?, C?) -> Unit) {
193-
a.observeForever {
192+
inline fun <reified A, reified B, reified C> LifecycleOwner.observe(a: LiveData<A>, b: LiveData<B>, c: LiveData<C>, crossinline handler: (A?, B?, C?) -> Unit) {
193+
a.observe(this, Observer {
194194
handler(a.value, b.value, c.value)
195-
}
196-
b.observeForever {
195+
})
196+
b.observe(this, Observer {
197197
handler(a.value, b.value, c.value)
198-
}
199-
c.observeForever {
198+
})
199+
c.observe(this, Observer {
200200
handler(a.value, b.value, c.value)
201-
}
201+
})
202202
}
203203

204204

app/src/main/java/com/mozzarelly/cbthelper/MainActivity.kt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,6 @@ inline fun <reified VM : CBTViewModel> CBTActivity<VM>.cbtViewModel(): Lazy<VM>
129129
override fun <T : ViewModel> create(modelClass: Class<T>): T {
130130
return modelClass.newInstance().also {
131131
(it as VM).run {
132-
applicationContext = this@cbtViewModel.applicationContext
133132
setup()
134133
}
135134
}

app/src/main/java/com/mozzarelly/cbthelper/Models.kt

Lines changed: 45 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ interface Model {
99
val id: Int
1010
val started: Boolean
1111
val complete: Boolean
12+
13+
fun textSummary(): String
1214
}
1315

1416
interface EntryModel : Model {
@@ -31,25 +33,25 @@ interface EntryModel : Model {
3133
var bottled: Boolean
3234
var marked: Boolean
3335

34-
fun copyFrom(model: EntryModel) {
35-
id = model.id
36-
situation = model.situation
37-
emotion1Name = model.emotion1Name
38-
emotion2Name = model.emotion2Name
39-
emotion3Name = model.emotion3Name
40-
emotion1Intensity = model.emotion1Intensity
41-
emotion2Intensity = model.emotion2Intensity
42-
emotion3Intensity = model.emotion3Intensity
43-
complete = model.complete
44-
date = model.date
45-
situationType = model.situationType
46-
whoWhere = model.whoWhere
47-
thoughts = model.thoughts
48-
assumptions = model.assumptions
49-
expression = model.expression
50-
relationships = model.relationships
51-
bottled = model.bottled
52-
marked = model.marked
36+
fun copyFrom(model: EntryModel?) {
37+
id = model?.id ?: 0
38+
situation = model?.situation
39+
emotion1Name = model?.emotion1Name
40+
emotion2Name = model?.emotion2Name
41+
emotion3Name = model?.emotion3Name
42+
emotion1Intensity = model?.emotion1Intensity
43+
emotion2Intensity = model?.emotion2Intensity
44+
emotion3Intensity = model?.emotion3Intensity
45+
complete = model?.complete ?: false
46+
date = model?.date ?: LocalDateTime.now()
47+
situationType = model?.situationType ?: true
48+
whoWhere = model?.whoWhere
49+
thoughts = model?.thoughts
50+
assumptions = model?.assumptions
51+
expression = model?.expression
52+
relationships = model?.relationships
53+
bottled = model?.bottled ?: false
54+
marked = model?.marked ?: false
5355
}
5456

5557
val emotion1 get() = emotion1Name?.let { Emotion(it, emotion1Intensity ?: 6) }
@@ -59,10 +61,19 @@ interface EntryModel : Model {
5961
val emotions get() = listOfNotNull(emotion1, emotion2, emotion3)
6062
val emotionString get() = emotionText(emotion1, emotion2, emotion3)
6163
val emotionStringWithNewlines get() = emotionText(emotion1, emotion2, emotion3, delimiter1 = "\n", delimiter2 = "\n")
62-
val simpleEmotionString get() = emotionTextSimple(emotion1, emotion2, emotion3)
64+
val simpleEmotionString get() = emotions.toSimpleText()
65+
66+
val situationTypeText: String
67+
get() = if (situationType) "situation" else "conversation"
6368

6469
override val started: Boolean
6570
get() = situation != null
71+
72+
override fun textSummary(): String = """
73+
You described a $situationTypeText in which you felt $emotionString:
74+
75+
$situation
76+
""".trimIndent()
6677
}
6778

6879
@Entity
@@ -177,13 +188,14 @@ interface CogValidModel : Model{
177188
"Overshoulding".takeIf { answer7 in 1..3 },
178189
"Confusing wanting and needing".takeIf { answer7 == 4 },
179190
"Confusing needing and deserving".takeIf { answer7 == 5 },
180-
"Cognitive dissonance".takeIf { answer9 == 2 }
191+
"Cognitive dissonance".takeIf { answer9 == 1 }
181192
)
182193
}
183194

184195
val isRational: Boolean
185196
get() = errors().isEmpty()
186197

198+
override fun textSummary(): String = if (isRational) "No errors found." else "Errors found:\n\n" + errors().joinToString("\n")
187199
}
188200

189201
@Entity
@@ -254,11 +266,21 @@ interface RatRepModel : Model {
254266
val emotion2 get() = emotion2Name?.let { Emotion(it, emotion2Intensity ?: 6) }
255267
val emotion3 get() = emotion3Name?.let { Emotion(it, emotion3Intensity ?: 6) }
256268

269+
val emotionString get() = emotionText(emotion1, emotion2, emotion3)
270+
val emotions get() = listOfNotNull(emotion1, emotion2, emotion3)
271+
val simpleEmotionString get() = emotions.toSimpleText()
272+
257273
override val complete: Boolean
258274
get() = comparison != null
259275

260276
override val started: Boolean
261277
get() = thinkInstead != null
278+
279+
override fun textSummary(): String = """
280+
You discovered that you could have instead thought: “$thinkInstead
281+
282+
This would likely have helped you feel: $emotionString
283+
""".trimIndent()
262284
}
263285

264286
@Entity
@@ -296,9 +318,6 @@ data class RatRep(
296318
fun new(id: Int): RatRep = RatRep(id)
297319
}
298320

299-
val emotions get() = listOfNotNull(emotion1, emotion2, emotion3)
300-
val emotionString get() = emotionText(emotion1, emotion2, emotion3)
301-
val simpleEmotionString get() = emotionTextSimple(emotion1, emotion2, emotion3)
302321
}
303322

304323
interface BehaviorModel : Model {
@@ -348,6 +367,8 @@ interface BehaviorModel : Model {
348367

349368
val isRational: Boolean
350369
get() = errors().isEmpty()
370+
371+
override fun textSummary(): String = if (isRational) "No errors found." else "Errors found:\n\n" + errors().joinToString("\n")
351372
}
352373

353374
@Entity

app/src/main/java/com/mozzarelly/cbthelper/SettingsActivity.kt

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@ import android.os.Bundle
66
import androidx.appcompat.app.AlertDialog
77
import androidx.appcompat.app.AppCompatActivity
88
import androidx.appcompat.app.AppCompatDelegate
9+
import androidx.lifecycle.lifecycleScope
910
import androidx.preference.Preference
1011
import androidx.preference.PreferenceFragmentCompat
1112
import androidx.preference.SwitchPreferenceCompat
13+
import kotlinx.coroutines.Dispatchers
14+
import kotlinx.coroutines.launch
1215

1316
class SettingsActivity : AppCompatActivity() {
1417

@@ -58,10 +61,19 @@ class SettingsActivity : AppCompatActivity() {
5861
.setMessage("Delete all saved entries and analyses? Cannot be undone.")
5962
.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }
6063
.setPositiveButton(R.string.ok) { dialog, _ ->
61-
// lifecycleScope.launch {
62-
CBTDatabase.getDatabase(requireContext()).clearAllTables()
64+
lifecycleScope.launch(Dispatchers.IO) {
65+
CBTDatabase.getDatabase(requireContext()).clean()
6366
dialog.dismiss()
64-
// }
67+
}
68+
}.apply {
69+
if (BuildConfig.DEBUG){
70+
setNeutralButton("Repop"){ dialog, _ ->
71+
lifecycleScope.launch(Dispatchers.IO) {
72+
CBTDatabase.getDatabase(requireContext()).clean(true)
73+
dialog.dismiss()
74+
}
75+
}
76+
}
6577
}
6678
.show()
6779

app/src/main/java/com/mozzarelly/cbthelper/Utils.kt

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -283,9 +283,9 @@ fun intentToSendReminderNotification(context: Context, title: String?, message:
283283
PendingIntent.FLAG_UPDATE_CURRENT
284284
)
285285

286-
fun emotionTextSimple(vararg emotions: Emotion?): String? = emotionTextSimple(*emotions.map { it?.emotion }.toTypedArray())
286+
fun List<Emotion?>.toSimpleText(): String? = emotionTextSimple(mapNotNull { it?.emotion })
287287

288-
fun emotionTextSimple(vararg emotions: String?): String? = with (emotions.filterNotNull()){
288+
fun emotionTextSimple(emotions: List<String>): String? = with (emotions){
289289
when (size){
290290
0 -> null
291291
1 -> get(0)
@@ -381,16 +381,23 @@ fun KClass<*>.requestCode() = (hashCode() and 0x0000ffff).also { println("reques
381381

382382
fun <V : CBTViewModel> CBTActivity<V>.showSavedEntryDialog(id: Int){
383383
AlertDialog.Builder(this).apply {
384-
if (id >= 0) {
385-
setTitle("Entry saved")
386-
setMessage("Your entry has been recorded. Would you like to analyze it now or later?")
387-
setNegativeButton("Analyze later"){ dialog, _ -> dialog.dismiss() }
388-
setPositiveButton("Analyze now") { _, _ -> start<AnalyzeActivity>(id) }
389-
}
390-
else {
391-
setTitle(if (id >= 0) "Entry saved" else "Entry not saved!")
392-
setMessage(if (id >= 0) "Your entry has been recorded. Would you like to analyze it now or later?" else "Something went wrong. Your entry could not be saved.")
393-
setNegativeButton("OK"){ dialog, _ -> dialog.dismiss() }
384+
when {
385+
id > 0 -> {
386+
setTitle("Entry saved")
387+
setMessage("Your entry has been recorded. Would you like to analyze it now or later?")
388+
setNegativeButton("Analyze later") { dialog, _ -> dialog.dismiss() }
389+
setPositiveButton("Analyze now") { _, _ -> start<AnalyzeActivity>(id) }
390+
}
391+
id < 0 -> {
392+
setTitle("Entry not saved!")
393+
setMessage("Something went wrong. Your entry could not be saved.")
394+
setNegativeButton("OK") { dialog, _ -> dialog.dismiss() }
395+
}
396+
else -> {
397+
setTitle("Entry saved")
398+
setMessage("Your entry in progress has been saved and can be continued later.")
399+
setNegativeButton("OK") { dialog, _ -> dialog.dismiss() }
400+
}
394401
}
395402

396403
show()

0 commit comments

Comments
 (0)