Sources/OrgWatchData/WatchAgenda.swift
188 lines · 7410 bytes
1import Foundation
2
3/// What the watch shows, sent by the phone over WatchConnectivity: today's agenda, the running
4/// clock and the entry Clock In Last would take. The watch keeps the last one it got.
5public struct WatchAgenda: Codable, Equatable, Sendable {
6 public struct Entry: Codable, Equatable, Sendable, Identifiable {
7 public var id: String
8 public var title: String
9 /// The agenda's gutter: the time or a short status.
10 public var gutter: String
11 public var category: String
12 public var todo: String?
13 /// `AgendaRow.Status`'s raw value: `overdue`, `due-soon`, `normal`, `done`.
14 public var status: String
15 public var isDone: Bool
16 public var isEvent: Bool
17 public var start: Date?
18 public var end: Date?
19 /// Where the entry is, and its heading line, for the phone to find it again.
20 public var path: String?
21 public var offset: Int?
22 public var headingLine: String?
23 /// The keyword marking it done takes: the first done keyword of its sequence.
24 public var doneKeyword: String?
25
26 public init(
27 id: String, title: String, gutter: String, category: String, todo: String?, status: String, isDone: Bool, isEvent: Bool,
28 start: Date?, end: Date?, path: String?, offset: Int?, headingLine: String?, doneKeyword: String?
29 ) {
30 self.id = id
31 self.title = title
32 self.gutter = gutter
33 self.category = category
34 self.todo = todo
35 self.status = status
36 self.isDone = isDone
37 self.isEvent = isEvent
38 self.start = start
39 self.end = end
40 self.path = path
41 self.offset = offset
42 self.headingLine = headingLine
43 self.doneKeyword = doneKeyword
44 }
45
46 /// An open TODO entry the phone can find.
47 public var canBeDone: Bool {
48 !isDone && !isEvent && todo != nil && doneKeyword != nil && path != nil && offset != nil && headingLine != nil
49 }
50
51 /// The action marking it done.
52 public var done: WatchAction? {
53 guard canBeDone, let path, let offset, let headingLine, let doneKeyword else { return nil }
54 return .done(path: path, offset: offset, headingLine: headingLine, keyword: doneKeyword)
55 }
56 }
57
58 public struct Clock: Codable, Equatable, Sendable {
59 public var heading: String
60 public var startedAt: Date
61
62 public init(heading: String, startedAt: Date) {
63 self.heading = heading
64 self.startedAt = startedAt
65 }
66 }
67
68 public var generated: Date
69 /// Midnight starting today.
70 public var day: Date
71 /// Deadlines and scheduled entries from before today.
72 public var overdue: [Entry]
73 public var rows: [Entry]
74 public var clock: Clock?
75 /// The most recently clocked entry, `org-clock-in-last`'s.
76 public var lastClocked: String?
77
78 public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) {
79 self.generated = generated
80 self.day = day
81 self.overdue = overdue
82 self.rows = rows
83 self.clock = clock
84 self.lastClocked = lastClocked
85 }
86
87 /// What's left of today at `now`, as the Up Next widget counts it: entries that aren't
88 /// done, without timed ones that have ended (or started, with no end), then the overdue.
89 public func upcoming(at now: Date, calendar: Calendar = .current) -> [Entry] {
90 guard calendar.isDate(day, inSameDayAs: now) else { return [] }
91 let left = rows.filter { row in
92 guard !row.isDone else { return false }
93 if let end = row.end ?? row.start { return end > now }
94 return true
95 }
96 return left + overdue.filter { !$0.isDone }
97 }
98
99 /// The first of `upcoming`.
100 public func next(at now: Date, calendar: Calendar = .current) -> Entry? { upcoming(at: now, calendar: calendar).first }
101
102 /// Open TODO entries today and overdue, as the complication counts them.
103 public func openCount(at now: Date, calendar: Calendar = .current) -> Int {
104 guard calendar.isDate(day, inSameDayAs: now) else { return 0 }
105 return (rows + overdue).filter { !$0.isDone && !$0.isEvent && $0.todo != nil }.count
106 }
107
108 /// `entry` marked done here before the phone sends the agenda again.
109 public func markingDone(_ id: String) -> WatchAgenda {
110 var copy = self
111 func mark(_ rows: inout [Entry]) {
112 for i in rows.indices where rows[i].id == id {
113 rows[i].isDone = true
114 rows[i].todo = rows[i].doneKeyword
115 rows[i].status = "done"
116 }
117 }
118 mark(©.rows)
119 mark(©.overdue)
120 return copy
121 }
122
123 // MARK: - Transfer
124
125 static var encoder: JSONEncoder {
126 let encoder = JSONEncoder()
127 encoder.dateEncodingStrategy = .iso8601
128 encoder.outputFormatting = [.sortedKeys]
129 return encoder
130 }
131
132 static var decoder: JSONDecoder {
133 let decoder = JSONDecoder()
134 decoder.dateDecodingStrategy = .iso8601
135 return decoder
136 }
137
138 /// The application context key the agenda travels under.
139 public static let contextKey = "agenda"
140
141 public func data() throws -> Data { try Self.encoder.encode(self) }
142
143 public static func decode(_ data: Data) -> WatchAgenda? { try? decoder.decode(WatchAgenda.self, from: data) }
144
145 /// `Widgets/watch.json` in the app group's container, which the complications read; nil
146 /// without the group.
147 public static func file(group: String = "group.sh.krz.orgstar") -> URL? {
148 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
149 .appendingPathComponent("Widgets").appendingPathComponent("watch.json")
150 }
151
152 public static func read(from file: URL? = file()) -> WatchAgenda? {
153 file.flatMap { try? Data(contentsOf: $0) }.flatMap(decode)
154 }
155
156 /// Writes unless the file holds the same; true when it wrote.
157 @discardableResult
158 public func write(to file: URL? = WatchAgenda.file()) throws -> Bool {
159 guard let file, Self.read(from: file) != self else { return false }
160 try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
161 try data().write(to: file, options: .atomic)
162 return true
163 }
164}
165
166/// What the watch asks the phone to do.
167public enum WatchAction: Codable, Equatable, Sendable {
168 /// Sets the entry's keyword to `keyword`, if its heading line is still `headingLine`.
169 case done(path: String, offset: Int, headingLine: String, keyword: String)
170 case clockOut
171 /// `org-clock-in-last`.
172 case clockInLast
173 /// Dictated text for the capture inbox.
174 case capture(text: String)
175
176 /// The user info key an action travels under.
177 public static let key = "action"
178
179 public var userInfo: [String: Any] {
180 guard let data = try? WatchAgenda.encoder.encode(self) else { return [:] }
181 return [Self.key: data]
182 }
183
184 public init?(userInfo: [String: Any]) {
185 guard let data = userInfo[Self.key] as? Data, let action = try? WatchAgenda.decoder.decode(WatchAction.self, from: data) else { return nil }
186 self = action
187 }
188}