Sources/OrgWatchData/WatchAgenda.swift

197 lines · 7815 bytes

15 symbols in this file
  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    /// True when the phone hasn't got orgstar+, which the Watch app needs.
 78    public var locked: Bool?
 79
 80    /// What the phone sends without Pro: no entries.
 81    public static func locked(generated: Date) -> WatchAgenda {
 82        var agenda = WatchAgenda(generated: generated, day: generated, overdue: [], rows: [], clock: nil, lastClocked: nil)
 83        agenda.locked = true
 84        return agenda
 85    }
 86
 87    public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) {
 88        self.generated = generated
 89        self.day = day
 90        self.overdue = overdue
 91        self.rows = rows
 92        self.clock = clock
 93        self.lastClocked = lastClocked
 94    }
 95
 96    /// What's left of today at `now`, as the Up Next widget counts it: entries that aren't
 97    /// done, without timed ones that have ended (or started, with no end), then the overdue.
 98    public func upcoming(at now: Date, calendar: Calendar = .current) -> [Entry] {
 99        guard calendar.isDate(day, inSameDayAs: now) else { return [] }
100        let left = rows.filter { row in
101            guard !row.isDone else { return false }
102            if let end = row.end ?? row.start { return end > now }
103            return true
104        }
105        return left + overdue.filter { !$0.isDone }
106    }
107
108    /// The first of `upcoming`.
109    public func next(at now: Date, calendar: Calendar = .current) -> Entry? { upcoming(at: now, calendar: calendar).first }
110
111    /// Open TODO entries today and overdue, as the complication counts them.
112    public func openCount(at now: Date, calendar: Calendar = .current) -> Int {
113        guard calendar.isDate(day, inSameDayAs: now) else { return 0 }
114        return (rows + overdue).filter { !$0.isDone && !$0.isEvent && $0.todo != nil }.count
115    }
116
117    /// `entry` marked done here before the phone sends the agenda again.
118    public func markingDone(_ id: String) -> WatchAgenda {
119        var copy = self
120        func mark(_ rows: inout [Entry]) {
121            for i in rows.indices where rows[i].id == id {
122                rows[i].isDone = true
123                rows[i].todo = rows[i].doneKeyword
124                rows[i].status = "done"
125            }
126        }
127        mark(&copy.rows)
128        mark(&copy.overdue)
129        return copy
130    }
131
132    // MARK: - Transfer
133
134    static var encoder: JSONEncoder {
135        let encoder = JSONEncoder()
136        encoder.dateEncodingStrategy = .iso8601
137        encoder.outputFormatting = [.sortedKeys]
138        return encoder
139    }
140
141    static var decoder: JSONDecoder {
142        let decoder = JSONDecoder()
143        decoder.dateDecodingStrategy = .iso8601
144        return decoder
145    }
146
147    /// The application context key the agenda travels under.
148    public static let contextKey = "agenda"
149
150    public func data() throws -> Data { try Self.encoder.encode(self) }
151
152    public static func decode(_ data: Data) -> WatchAgenda? { try? decoder.decode(WatchAgenda.self, from: data) }
153
154    /// `Widgets/watch.json` in the app group's container, which the complications read; nil
155    /// without the group.
156    public static func file(group: String = "group.sh.krz.orgstar") -> URL? {
157        FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
158            .appendingPathComponent("Widgets").appendingPathComponent("watch.json")
159    }
160
161    public static func read(from file: URL? = file()) -> WatchAgenda? {
162        file.flatMap { try? Data(contentsOf: $0) }.flatMap(decode)
163    }
164
165    /// Writes unless the file holds the same; true when it wrote.
166    @discardableResult
167    public func write(to file: URL? = WatchAgenda.file()) throws -> Bool {
168        guard let file, Self.read(from: file) != self else { return false }
169        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
170        try data().write(to: file, options: .atomic)
171        return true
172    }
173}
174
175/// What the watch asks the phone to do.
176public enum WatchAction: Codable, Equatable, Sendable {
177    /// Sets the entry's keyword to `keyword`, if its heading line is still `headingLine`.
178    case done(path: String, offset: Int, headingLine: String, keyword: String)
179    case clockOut
180    /// `org-clock-in-last`.
181    case clockInLast
182    /// Dictated text for the capture inbox.
183    case capture(text: String)
184
185    /// The user info key an action travels under.
186    public static let key = "action"
187
188    public var userInfo: [String: Any] {
189        guard let data = try? WatchAgenda.encoder.encode(self) else { return [:] }
190        return [Self.key: data]
191    }
192
193    public init?(userInfo: [String: Any]) {
194        guard let data = userInfo[Self.key] as? Data, let action = try? WatchAgenda.decoder.decode(WatchAction.self, from: data) else { return nil }
195        self = action
196    }
197}