ChartAxisSetup.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import CoreData
  2. import Foundation
  3. extension Home.StateModel {
  4. /// Recomputes the main glucose chart Y axis bounds from the fetched glucose objects.
  5. /// Runs on the main actor since the inputs are viewContext managed objects.
  6. @MainActor func updateGlucoseChartYAxis(glucoseValues: [GlucoseStored]) {
  7. let glucoseMapped = glucoseValues.map { Decimal($0.glucose) }
  8. let forecastValues = preprocessedData.map { Decimal($0.forecastValue.value) }
  9. // Ensure all values exist, otherwise set default values
  10. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  11. minYAxisValue = 39
  12. maxYAxisValue = 200
  13. return
  14. }
  15. let minForecast = forecastValues.min()
  16. let maxForecast = forecastValues.max()
  17. // Adjust max forecast to be no more than 50 over max glucose
  18. let adjustedMaxForecast = min(maxForecast ?? maxGlucose + 50, maxGlucose + 50)
  19. let minOverall = min(minGlucose, minForecast ?? minGlucose)
  20. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  21. var maxYValue: Decimal = 200
  22. if maxOverall > 200, maxOverall <= 225 {
  23. maxYValue = 250
  24. } else if maxOverall > 225, maxOverall <= 275 {
  25. maxYValue = 300
  26. } else if maxOverall > 275, maxOverall <= 325 {
  27. maxYValue = 350
  28. } else if maxOverall > 325 {
  29. maxYValue = 400
  30. }
  31. minYAxisValue = minOverall
  32. maxYAxisValue = maxYValue
  33. }
  34. /// Recomputes the COB chart Y axis bounds from the fetched determination objects.
  35. @MainActor func yAxisChartDataCobChart(determinations: [OrefDetermination]) {
  36. let cobMapped = determinations.map { Decimal($0.cob) }
  37. if let maxCob = cobMapped.max() {
  38. minValueCobChart = 0
  39. maxValueCobChart = maxCob == 0 ? 20 : maxCob + 20
  40. } else {
  41. minValueCobChart = 0
  42. maxValueCobChart = 20
  43. }
  44. }
  45. /// Recomputes the IOB chart Y axis bounds from the fetched determination objects.
  46. @MainActor func yAxisChartDataIobChart(determinations: [OrefDetermination]) {
  47. let iobMapped = determinations.compactMap { $0.iob?.decimalValue }
  48. if let minIob = iobMapped.min(), let maxIob = iobMapped.max() {
  49. minValueIobChart = minIob
  50. maxValueIobChart = maxIob
  51. } else {
  52. minValueIobChart = 0
  53. maxValueIobChart = 5
  54. }
  55. }
  56. }