-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDosesViewModel.swift
executable file
·84 lines (67 loc) · 2.61 KB
/
DosesViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// DosesViewModel.swift
// PainMedsBuddy
//
// Created by Jules Moorhouse.
//
import CoreData
import Foundation
extension DosesView {
class ViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate {
private let dataController: DataController
let showElapsedDoses: Bool
private let dosesController: NSFetchedResultsController<Dose>
@Published private var doses = [Dose]()
var medsCount: Int {
let medRequest = NSFetchRequest<Med>(entityName: "Med")
return dataController.count(for: medRequest)
}
// MARK: -
init(dataController: DataController, showElapsedDoses: Bool) {
self.dataController = dataController
self.showElapsedDoses = showElapsedDoses
let doseRequest: NSFetchRequest<Dose> = Dose.fetchRequest()
doseRequest.sortDescriptors = [
NSSortDescriptor(keyPath: \Dose.takenDate, ascending: false),
]
doseRequest.predicate = NSPredicate(format: "elapsed = %d", showElapsedDoses)
dosesController = NSFetchedResultsController(
fetchRequest: doseRequest,
managedObjectContext: dataController.container.viewContext,
sectionNameKeyPath: nil,
cacheName: nil
)
super.init()
dosesController.delegate = self
do {
try dosesController.performFetch()
doses = dosesController.fetchedObjects ?? []
} catch {
print("ERROR: Failed to fetch our doses: \(error)")
}
}
func deleteDose(_ offsets: IndexSet, from doses: [Dose]) {
for offset in offsets {
let item = doses[offset]
dataController.delete(item)
}
dataController.save()
}
// INFO: Results to an array of section arrays
func resultsToArray() -> [[Dose]] {
let dict = Dictionary(grouping: doses) { (sequence: Dose) in
sequence.doseFormattedTakenDateLong
}
// INFO: Sort by key aka doseFormattedTakenDateLong
let sorted = dict.sorted(by: { $0.key > $1.key })
return sorted.map(\.value)
}
func createMed() -> Med {
dataController.createMed()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
print("### DosesViewModel - controllerDidChangeContent")
doses = dosesController.fetchedObjects ?? []
}
}
}