DayByDay/Profiles/ProfileStore.swift
161 lines · 6945 bytes
18 symbols in this file
1//
2// ProfileStore.swift
3// DayByDay
4//
5
6import Foundation
7import SwiftData
8
9enum ProfileError: Error, Equatable {
10 case blankName
11 case invalidBirthday
12}
13
14final class ProfileStore {
15 let context: ModelContext
16
17 init(context: ModelContext) {
18 self.context = context
19 }
20
21 /// Stickers and day pictures were added after the first release as new
22 /// entities only, so earlier stores migrate without a versioned schema.
23 static let modelTypes: [any PersistentModel.Type] = [Profile.self, AnswerRecord.self, Sticker.self, DayPicture.self]
24
25 static func makeContainer(inMemory: Bool) -> ModelContainer {
26 let config = ModelConfiguration(isStoredInMemoryOnly: inMemory)
27 return try! ModelContainer(for: Schema(modelTypes), configurations: config)
28 }
29
30 func all() -> [Profile] {
31 let descriptor = FetchDescriptor<Profile>(sortBy: [SortDescriptor(\.createdAt)])
32 return (try? context.fetch(descriptor)) ?? []
33 }
34
35 @discardableResult
36 func create(name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws -> Profile {
37 let name = try Self.validName(name)
38 try Self.validate(birthday)
39 let profile = Profile(name: name, avatar: avatar, color: color,
40 birthdayMonth: birthday?.month, birthdayDay: birthday?.day)
41 context.insert(profile)
42 try? context.save()
43 return profile
44 }
45
46 func update(_ profile: Profile, name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws {
47 let name = try Self.validName(name)
48 try Self.validate(birthday)
49 profile.name = name
50 profile.avatarRaw = avatar.rawValue
51 profile.colorRaw = color.rawValue
52 profile.birthdayMonth = birthday?.month
53 profile.birthdayDay = birthday?.day
54 try? context.save()
55 }
56
57 func delete(_ profile: Profile) {
58 let id = profile.id
59 try? context.delete(model: Sticker.self, where: #Predicate { $0.profileID == id })
60 try? context.delete(model: DayPicture.self, where: #Predicate { $0.profileID == id })
61 context.delete(profile)
62 try? context.save()
63 }
64
65 /// `item` is the question's answer; `chosen` is what the child tapped.
66 func record(_ item: QuizItem, chosen: QuizItem? = nil, game: Game? = nil, correct: Bool,
67 for profile: Profile, at date: Date = .now) {
68 context.insert(AnswerRecord(categoryRaw: item.category.rawValue, itemID: item.id,
69 chosenID: chosen?.id, gameRaw: game?.rawValue,
70 isCorrect: correct, timestamp: date, profile: profile))
71 try? context.save()
72 }
73
74 func answers(for profile: Profile, category: Category?) -> [AnswerRecord] {
75 profile.answers
76 .filter { category == nil || $0.categoryRaw == category!.rawValue }
77 .sorted { $0.timestamp < $1.timestamp }
78 }
79
80 /// Games where an answer shows whether the child recognizes the item.
81 /// Tracing, sorting, ordering and comparing are left out. Answers with
82 /// no game were recorded before part 2 and are kept.
83 static let recognitionGames: Set<String> = Set([Game.findIt, .listen, .oddOneOut, .comesNext, .whichSeason].map(\.rawValue))
84
85 func progress(for profile: Profile, category: Category) -> ItemProgress {
86 ItemProgress(answers(for: profile, category: category)
87 .filter { $0.gameRaw.map(Self.recognitionGames.contains) ?? true }
88 .map { AnswerFact(itemID: $0.itemID, isCorrect: $0.isCorrect, timestamp: $0.timestamp) })
89 }
90
91 /// Pick weights for the topic's items the child is missing; the rest
92 /// weigh 1. Empty when nothing is being missed.
93 func reviewWeights(for profile: Profile, category: Category) -> [QuizItem: Double] {
94 let progress = progress(for: profile, category: category)
95 return Dictionary(uniqueKeysWithValues: category.quizItems.compactMap { item in
96 let weight = progress.weight(item.id)
97 return weight > 1 ? (item, weight) : nil
98 })
99 }
100
101 /// Days per month in a leap year, so February 29 birthdays are allowed.
102 static let daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
103
104 private static func validName(_ name: String) throws -> String {
105 let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
106 guard !trimmed.isEmpty else { throw ProfileError.blankName }
107 return trimmed
108 }
109
110 private static func validate(_ birthday: (month: Int, day: Int)?) throws {
111 guard let birthday else { return }
112 guard (1...12).contains(birthday.month),
113 (1...daysInMonth[birthday.month - 1]).contains(birthday.day)
114 else { throw ProfileError.invalidBirthday }
115 }
116
117 // MARK: - Stickers
118
119 /// Adds the day's sticker, or changes its weather if there is one.
120 func addSticker(for profile: Profile, on date: DateComponents, weather: LearnWeather) {
121 if let existing = sticker(for: profile, on: date) {
122 existing.weatherRaw = weather.rawValue
123 } else {
124 context.insert(Sticker(profileID: profile.id, year: date.year!, month: date.month!,
125 day: date.day!, weather: weather))
126 }
127 try? context.save()
128 }
129
130 func sticker(for profile: Profile, on date: DateComponents) -> Sticker? {
131 let id = profile.id, y = date.year!, m = date.month!, d = date.day!
132 let descriptor = FetchDescriptor<Sticker>(predicate: #Predicate {
133 $0.profileID == id && $0.year == y && $0.month == m && $0.day == d
134 })
135 return try? context.fetch(descriptor).first
136 }
137
138 func stickers(for profile: Profile, year: Int, month: Int) -> [Sticker] {
139 let id = profile.id
140 let descriptor = FetchDescriptor<Sticker>(predicate: #Predicate {
141 $0.profileID == id && $0.year == year && $0.month == month
142 }, sortBy: [SortDescriptor(\.day)])
143 return (try? context.fetch(descriptor)) ?? []
144 }
145
146 // MARK: - Day pictures
147
148 /// Sets or, with nil, removes the child's picture for a weekday.
149 func setPicture(_ kind: DayPictureKind?, on weekday: DayOfWeek, for profile: Profile) {
150 let id = profile.id, w = weekday.rawValue
151 try? context.delete(model: DayPicture.self, where: #Predicate { $0.profileID == id && $0.weekdayRaw == w })
152 if let kind { context.insert(DayPicture(profileID: id, weekday: weekday, kind: kind)) }
153 try? context.save()
154 }
155
156 func picture(on weekday: DayOfWeek, for profile: Profile) -> DayPictureKind? {
157 let id = profile.id, w = weekday.rawValue
158 let descriptor = FetchDescriptor<DayPicture>(predicate: #Predicate { $0.profileID == id && $0.weekdayRaw == w })
159 return (try? context.fetch(descriptor).first)?.kind
160 }
161}