forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInsulinSensitivityScheduleViewController.swift
More file actions
394 lines (321 loc) · 14.4 KB
/
Copy pathInsulinSensitivityScheduleViewController.swift
File metadata and controls
394 lines (321 loc) · 14.4 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//
// InsulinSensitivityScheduleViewController.swift
// LoopKitUI
//
// Created by Pete Schwamb on 7/2/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopAlgorithm
import LoopKit
public enum SaveInsulinSensitivityScheduleResult {
case success
case failure(Error)
}
public protocol InsulinSensitivityScheduleStorageDelegate {
func saveSchedule(_ schedule: InsulinSensitivitySchedule, for viewController: InsulinSensitivityScheduleViewController, completion: @escaping (_ result: SaveInsulinSensitivityScheduleResult) -> Void)
}
public class InsulinSensitivityScheduleViewController : DailyValueScheduleTableViewController {
public init(allowedValues: [Double], unit: LoopUnit, minimumTimeInterval: TimeInterval = TimeInterval(30 * 60)) {
self.allowedValues = allowedValues
self.minimumTimeInterval = minimumTimeInterval
self.unit = unit
super.init(style: .grouped)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
super.viewDidLoad()
tableView.register(SetConstrainedScheduleEntryTableViewCell.nib(), forCellReuseIdentifier: SetConstrainedScheduleEntryTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
updateEditButton()
}
@objc private func cancel(_ sender: Any?) {
self.navigationController?.popViewController(animated: true)
}
// MARK: - State
public var insulinSensitivityScheduleStorageDelegate: InsulinSensitivityScheduleStorageDelegate?
public var unit: LoopUnit = .milligramsPerDeciliterPerInternationalUnit
public var schedule: InsulinSensitivitySchedule? {
get {
let validEntries = internalItems.compactMap { (item) -> RepeatingScheduleValue<Double>? in
guard let value = item.value else {
return nil
}
return RepeatingScheduleValue(startTime: item.startTime, value: value)
}
return InsulinSensitivitySchedule(unit: unit, dailyItems: validEntries, timeZone: timeZone)
}
set {
if let newValue = newValue {
unit = newValue.unit
internalItems = newValue.items.map { (entry) -> RepeatingScheduleValue<Double?> in
RepeatingScheduleValue(startTime: entry.startTime, value: entry.value)
}
isScheduleModified = false
} else {
internalItems = []
}
}
}
private var internalItems: [RepeatingScheduleValue<Double?>] = [] {
didSet {
isScheduleModified = true
updateInsertButton()
}
}
let allowedValues: [Double]
let minimumTimeInterval: TimeInterval
var lastValidStartTime: TimeInterval {
return TimeInterval.hours(24) - minimumTimeInterval
}
private var isScheduleModified = false {
didSet {
updateCancelButton()
updateSaveButton()
}
}
private func isValid(_ value: Double?) -> Bool {
guard let value = value else {
return false
}
return allowedValues.contains(value)
}
public var isScheduleValid: Bool {
return !internalItems.isEmpty &&
internalItems.allSatisfy { isValid($0.value) }
}
private func updateCancelButton() {
if isScheduleModified {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(_:)))
} else {
self.navigationItem.leftBarButtonItem = nil
}
}
private func updateSaveButton() {
if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: Section.save.rawValue)) as? TextButtonTableViewCell {
cell.isEnabled = !isEditing && isScheduleModified && isScheduleValid
}
}
private func updateEditButton() {
editButtonItem.isEnabled = internalItems.endIndex > 1
}
private func updateInsertButton() {
guard let lastItem = internalItems.last else {
return
}
insertButtonItem.isEnabled = !isEditing && lastItem.startTime < lastValidStartTime
}
override func addScheduleItem(_ sender: Any?) {
tableView.endEditing(false)
let startTime: TimeInterval
let value: Double?
if let lastItem = internalItems.last {
startTime = lastItem.startTime + minimumTimeInterval
value = lastItem.value
if startTime > lastValidStartTime {
return
}
} else {
startTime = TimeInterval(0)
value = nil
}
internalItems.append(
RepeatingScheduleValue(
startTime: startTime,
value: value
)
)
updateTimeLimitsForItemsAdjacent(to: internalItems.endIndex-1)
super.addScheduleItem(sender)
if internalItems.count == 1 {
let index = IndexPath(row: 0, section: Section.schedule.rawValue)
tableView.beginUpdates()
tableView.selectRow(at: index, animated: true, scrollPosition: .top)
tableView.deselectRow(at: index, animated: true)
tableView.endUpdates()
} else {
tableView.beginUpdates()
hideSetConstrainedScheduleEntryCells()
tableView.endUpdates()
}
updateEditButton()
}
override func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
return insertableIndices(for: internalItems, removing: row, with: timeInterval)
}
open override func setEditing(_ editing: Bool, animated: Bool) {
tableView.beginUpdates()
hideSetConstrainedScheduleEntryCells()
tableView.endUpdates()
super.setEditing(editing, animated: animated)
updateInsertButton()
updateSaveButton()
}
private func updateTimeLimitsFor(itemAt index: Int) {
guard internalItems.indices.contains(index) else {
return
}
let indexPath = IndexPath(row: index, section: Section.schedule.rawValue)
if let cell = tableView.cellForRow(at: indexPath) as? SetConstrainedScheduleEntryTableViewCell {
if index+1 < internalItems.endIndex {
cell.maximumStartTime = internalItems[index+1].startTime - minimumTimeInterval
} else {
cell.maximumStartTime = lastValidStartTime
}
if index > 1 {
cell.minimumStartTime = internalItems[index-1].startTime + minimumTimeInterval
}
}
}
private func updateTimeLimitsForItemsAdjacent(to index: Int) {
updateTimeLimitsFor(itemAt: index-1)
updateTimeLimitsFor(itemAt: index+1)
}
// MARK: - UITableViewDataSource
private enum Section: Int, CaseIterable {
case schedule
case save
}
open override func numberOfSections(in tableView: UITableView) -> Int {
return Section.allCases.count
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .schedule:
return internalItems.endIndex
case .save:
return 1
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .schedule:
let cell = tableView.dequeueReusableCell(withIdentifier: SetConstrainedScheduleEntryTableViewCell.className, for: indexPath) as! SetConstrainedScheduleEntryTableViewCell
switch unit {
case .milligramsPerDeciliter:
cell.unit = .milligramsPerDeciliterPerInternationalUnit
case .millimolesPerLiter:
cell.unit = .millimolesPerLiterPerInternationalUnit
default:
break
}
let item = internalItems[indexPath.row]
cell.allowedValues = allowedValues
cell.minimumTimeInterval = minimumTimeInterval
cell.isReadOnly = false
cell.isPickerHidden = true
cell.delegate = self
cell.timeZone = timeZone
if indexPath.row > 0 {
let lastItem = internalItems[indexPath.row - 1]
cell.minimumStartTime = lastItem.startTime + minimumTimeInterval
}
if indexPath.row == 0 {
cell.maximumStartTime = 0
} else if indexPath.row < internalItems.endIndex - 1 {
let nextItem = internalItems[indexPath.row + 1]
cell.maximumStartTime = nextItem.startTime - minimumTimeInterval
} else {
cell.maximumStartTime = lastValidStartTime
}
cell.value = item.value
cell.startTime = item.startTime
cell.emptySelectionType = .lastIndex
return cell
case .save:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = LocalizedString("Save", comment: "Button text for saving insulin sensitivity schedule")
cell.isEnabled = isScheduleModified && isScheduleValid
return cell
}
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .schedule:
return LocalizedString("Insulin sensitivity describes how your blood glucose should respond to a 1 Unit dose of insulin. Smaller values mean more insulin will be given when above target. Values that are too small can cause dangerously low blood glucose.", comment: "The description shown on the insulin sensitivity schedule interface.")
case .save:
return nil
}
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
internalItems.remove(at: indexPath.row)
super.tableView(tableView, commit: editingStyle, forRowAt: indexPath)
if internalItems.count == 1 {
self.isEditing = false
}
updateInsertButton()
updateEditButton()
updateTimeLimitsFor(itemAt: indexPath.row-1)
updateTimeLimitsFor(itemAt: indexPath.row)
updateSaveButton()
}
}
open override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
let item = internalItems.remove(at: sourceIndexPath.row)
internalItems.insert(item, at: destinationIndexPath.row)
let startTime = internalItems[destinationIndexPath.row - 1].startTime + minimumTimeInterval
internalItems[destinationIndexPath.row] = RepeatingScheduleValue(startTime: startTime, value: internalItems[destinationIndexPath.row].value)
DispatchQueue.main.async {
tableView.reloadRows(at: [destinationIndexPath], with: .none)
self.updateTimeLimitsForItemsAdjacent(to: destinationIndexPath.row)
}
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
guard indexPath.section == Section.schedule.rawValue else {
return super.tableView(tableView, shouldHighlightRowAt: indexPath)
}
return !isReadOnly
}
open override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
tableView.beginUpdates()
hideSetConstrainedScheduleEntryCells(excluding: indexPath)
tableView.endUpdates()
return super.tableView(tableView, willSelectRowAt: indexPath)
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch Section(rawValue: indexPath.section)! {
case .schedule:
break
case .save:
if let schedule = schedule {
insulinSensitivityScheduleStorageDelegate?.saveSchedule(schedule, for: self, completion: { (result) in
switch result {
case .success:
self.delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
self.isScheduleModified = false
self.updateInsertButton()
case .failure(let error):
self.present(UIAlertController(with: error), animated: true)
}
})
}
}
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? SetConstrainedScheduleEntryTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.minimumTimeInterval
let indices = insertableIndices(for: internalItems, removing: sourceIndexPath.row, with: interval)
let closestDestinationRow = indices.insertableIndex(closestTo: proposedDestinationIndexPath.row, from: sourceIndexPath.row)
return IndexPath(row: closestDestinationRow, section: proposedDestinationIndexPath.section)
}
}
extension InsulinSensitivityScheduleViewController: SetConstrainedScheduleEntryTableViewCellDelegate {
func setConstrainedScheduleEntryTableViewCellDidUpdate(_ cell: SetConstrainedScheduleEntryTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
internalItems[indexPath.row] = RepeatingScheduleValue(
startTime: cell.startTime,
value: cell.value
)
updateTimeLimitsForItemsAdjacent(to: indexPath.row)
}
}
}