GlucoseChart.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // GlucoseChart.swift
  3. // LoopUI
  4. //
  5. // Copyright © 2019 LoopKit Authors. All rights reserved.
  6. //
  7. import Foundation
  8. import HealthKit
  9. import LoopKit
  10. import SwiftCharts
  11. open class GlucoseChart {
  12. public init() {
  13. }
  14. public var glucoseUnit: HKUnit = .milligramsPerDeciliter {
  15. didSet {
  16. if glucoseUnit != oldValue {
  17. // Regenerate the glucose display points
  18. let oldRange = glucoseDisplayRange
  19. glucoseDisplayRange = oldRange
  20. }
  21. }
  22. }
  23. public var glucoseDisplayRange: ClosedRange<HKQuantity>? {
  24. didSet {
  25. if let range = glucoseDisplayRange {
  26. glucoseDisplayRangePoints = [
  27. ChartPoint(x: ChartAxisValue(scalar: 0), y: ChartAxisValueDouble(range.lowerBound.doubleValue(for: glucoseUnit))),
  28. ChartPoint(x: ChartAxisValue(scalar: 0), y: ChartAxisValueDouble(range.upperBound.doubleValue(for: glucoseUnit)))
  29. ]
  30. } else {
  31. glucoseDisplayRangePoints = []
  32. }
  33. }
  34. }
  35. public private(set) var glucoseDisplayRangePoints: [ChartPoint] = []
  36. public func glucosePointsFromValues(_ glucoseValues: [GlucoseValue]) -> [ChartPoint] {
  37. let unitFormatter = QuantityFormatter(for: glucoseUnit)
  38. unitFormatter.unitStyle = .short
  39. let unitString = unitFormatter.localizedUnitStringWithPlurality()
  40. let dateFormatter = DateFormatter(timeStyle: .short)
  41. return glucoseValues.map {
  42. return ChartPoint(
  43. x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter),
  44. y: ChartAxisValueDoubleUnit($0.quantity.doubleValue(for: glucoseUnit), unitString: unitString, formatter: unitFormatter.numberFormatter)
  45. )
  46. }
  47. }
  48. }