DayByDay/Profiles/ProfileSession.swift
61 lines · 1565 bytes
6 symbols in this file
1//
2// ProfileSession.swift
3// DayByDay
4//
5
6import Foundation
7import Observation
8import SwiftData
9
10enum SessionScreen: Equatable {
11 case setup, picker, home
12}
13
14/// Tracks which child is using the app and which top-level screen to show.
15@Observable
16final class ProfileSession {
17 /// Time in the background after which siblings pick again.
18 static let pickerAfterBackground: TimeInterval = 600
19
20 let store: ProfileStore
21 private(set) var profiles: [Profile] = []
22 var current: Profile?
23 private var backgroundedAt: Date?
24
25 init(store: ProfileStore) {
26 self.store = store
27 profilesChanged()
28 }
29
30 var screen: SessionScreen {
31 if profiles.isEmpty { return .setup }
32 return current == nil ? .picker : .home
33 }
34
35 func select(_ profile: Profile) {
36 current = profile
37 }
38
39 func didEnterBackground(at date: Date) {
40 backgroundedAt = date
41 }
42
43 func willEnterForeground(at date: Date) {
44 defer { backgroundedAt = nil }
45 guard let backgroundedAt, profiles.count > 1,
46 date.timeIntervalSince(backgroundedAt) >= Self.pickerAfterBackground
47 else { return }
48 current = nil
49 }
50
51 /// Call after any profile is added, edited, or deleted.
52 func profilesChanged() {
53 profiles = store.all()
54 if let current, !profiles.contains(where: { $0.persistentModelID == current.persistentModelID }) {
55 self.current = nil
56 }
57 if current == nil, profiles.count == 1 {
58 current = profiles[0]
59 }
60 }
61}