forked from home-assistant/iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterfaceController.swift
177 lines (140 loc) · 6.12 KB
/
InterfaceController.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import Communicator
import EMTLoadingIndicator
import Foundation
import PromiseKit
import RealmSwift
import Shared
import WatchKit
class InterfaceController: WKInterfaceController {
@IBOutlet var tableView: WKInterfaceTable!
@IBOutlet var noActionsLabel: WKInterfaceLabel!
var notificationToken: NotificationToken?
var actions: Results<Action>?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
MaterialDesignIcons.register()
setupTable()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func setupTable() {
let realm = Realm.live()
noActionsLabel.setText(L10n.Watch.Labels.noAction)
let actions = realm.objects(Action.self).sorted(byKeyPath: "Position")
self.actions = actions
notificationToken = actions.observe { (changes: RealmCollectionChange) in
guard let tableView = self.tableView else { return }
self.noActionsLabel.setHidden(actions.count > 0)
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.setNumberOfRows(actions.count, withRowType: "actionRowType")
for idx in actions.indices {
self.setupRow(idx)
}
case let .update(_, deletions, insertions, modifications):
let insertionsSet = NSMutableIndexSet()
insertions.forEach(insertionsSet.add)
tableView.insertRows(at: IndexSet(insertionsSet), withRowType: "actionRowType")
insertions.forEach(self.setupRow)
let deletionsSet = NSMutableIndexSet()
deletions.forEach(deletionsSet.add)
tableView.removeRows(at: IndexSet(deletionsSet))
modifications.forEach(self.setupRow)
case let .error(error):
// An error occurred while opening the Realm file on the background worker thread
Current.Log.error("Error during Realm notifications! \(error)")
}
}
}
func setupRow(_ index: Int) {
DispatchQueue.main.async {
guard let row = self.tableView.rowController(at: index) as? ActionRowType,
let action = self.actions?[index] else { return }
row.group.setBackgroundColor(UIColor(hex: action.BackgroundColor))
row.indicator = EMTLoadingIndicator(
interfaceController: self,
interfaceImage: row.image,
width: 24,
height: 24,
style: .dot
)
row.icon = MaterialDesignIcons(named: action.IconName)
let iconColor = UIColor(hex: action.IconColor)
row.image.setImage(row.icon.image(ofSize: CGSize(width: 24, height: 24), color: iconColor))
row.image.setAlpha(1)
row.label.setText(action.Text)
row.label.setTextColor(UIColor(hex: action.TextColor))
}
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
let selectedAction = actions![rowIndex]
Current.Log.verbose("Selected action row at index \(rowIndex), \(selectedAction)")
guard let row = tableView.rowController(at: rowIndex) as? ActionRowType else {
Current.Log.warning("Row at \(rowIndex) is not ActionRowType")
return
}
row.indicator?.prepareImagesForWait()
row.indicator?.showWait()
enum SendError: Error {
case notImmediate
case phoneFailed
}
firstly { () -> Promise<Void> in
Promise { seal in
guard Communicator.shared.currentReachability == .immediatelyReachable else {
seal.reject(SendError.notImmediate)
return
}
Current.Log.verbose("Signaling action pressed via phone")
let actionMessage = InteractiveImmediateMessage(
identifier: "ActionRowPressed",
content: ["ActionID": selectedAction.ID],
reply: { message in
Current.Log.verbose("Received reply dictionary \(message)")
if message.content["fired"] as? Bool == true {
seal.fulfill(())
} else {
seal.reject(SendError.phoneFailed)
}
}
)
Current.Log.verbose("Sending ActionRowPressed message \(actionMessage)")
Communicator.shared.send(actionMessage, errorHandler: { error in
Current.Log.error("Received error when sending immediate message \(error)")
seal.reject(error)
})
}
}.recover { error -> Promise<Void> in
guard error == SendError.notImmediate, let server = Current.servers.server(for: selectedAction) else {
throw error
}
Current.Log.error("recovering error \(error) by trying locally")
return Current.api(for: server).HandleAction(actionID: selectedAction.ID, source: .Watch)
}.done {
self.handleActionSuccess(row, rowIndex)
}.catch { err -> Void in
Current.Log.error("Error during action event fire: \(err)")
self.handleActionFailure(row, rowIndex)
}
}
func handleActionSuccess(_ row: ActionRowType, _ index: Int) {
WKInterfaceDevice.current().play(.success)
row.image.stopAnimating()
setupRow(index)
}
func handleActionFailure(_ row: ActionRowType, _ index: Int) {
WKInterfaceDevice.current().play(.failure)
row.image.stopAnimating()
setupRow(index)
}
deinit {
notificationToken?.invalidate()
}
}