StatRootView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. import Charts
  2. import CoreData
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. extension Stat {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. @FetchRequest(
  11. entity: Readings.entity(),
  12. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  13. format: "date >= %@", Calendar.current.startOfDay(for: Date()) as NSDate
  14. )
  15. ) var fetchedGlucoseDay: FetchedResults<Readings>
  16. @FetchRequest(
  17. entity: Readings.entity(),
  18. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
  19. predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(-24.hours.timeInterval) as NSDate)
  20. ) var fetchedGlucoseTwentyFourHours: FetchedResults<Readings>
  21. @FetchRequest(
  22. entity: Readings.entity(),
  23. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
  24. predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(-7.days.timeInterval) as NSDate)
  25. ) var fetchedGlucoseWeek: FetchedResults<Readings>
  26. @FetchRequest(
  27. entity: Readings.entity(),
  28. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  29. format: "date > %@",
  30. Date().addingTimeInterval(-30.days.timeInterval) as NSDate
  31. )
  32. ) var fetchedGlucoseMonth: FetchedResults<Readings>
  33. @FetchRequest(
  34. entity: Readings.entity(),
  35. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  36. format: "date > %@",
  37. Date().addingTimeInterval(-90.days.timeInterval) as NSDate
  38. )
  39. ) var fetchedGlucose: FetchedResults<Readings>
  40. @FetchRequest(
  41. entity: TDD.entity(),
  42. sortDescriptors: [NSSortDescriptor(key: "timestamp", ascending: false)]
  43. ) var fetchedTDD: FetchedResults<TDD>
  44. @FetchRequest(
  45. entity: LoopStatRecord.entity(),
  46. sortDescriptors: [NSSortDescriptor(key: "start", ascending: false)], predicate: NSPredicate(
  47. format: "start > %@",
  48. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  49. )
  50. ) var fetchedLoopStats: FetchedResults<LoopStatRecord>
  51. @FetchRequest(
  52. entity: InsulinDistribution.entity(),
  53. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  54. ) var fetchedInsulin: FetchedResults<InsulinDistribution>
  55. enum Duration: String, CaseIterable, Identifiable {
  56. case Today
  57. case Day
  58. case Week
  59. case Month
  60. case Total
  61. var id: Self { self }
  62. }
  63. @State private var selectedDuration: Duration = .Today
  64. @State var paddingAmount: CGFloat? = 10
  65. @State var headline: Color = .secondary
  66. @State var days: Double = 0
  67. @State var pointSize: CGFloat = 3
  68. @State var conversionFactor = 0.0555
  69. @ViewBuilder func stats() -> some View {
  70. if state.layingChart ?? true {
  71. bloodGlucose
  72. Divider()
  73. } else {
  74. bloodGlucose
  75. Divider()
  76. standingTIRchart
  77. Divider()
  78. }
  79. loops
  80. Divider()
  81. hba1c
  82. }
  83. @ViewBuilder func chart() -> some View {
  84. switch selectedDuration {
  85. case .Today:
  86. glucoseChart
  87. case .Day:
  88. glucoseChartTwentyFourHours
  89. case .Week:
  90. glucoseChartWeek
  91. case .Month:
  92. glucoseChartMonth
  93. case .Total:
  94. glucoseChart90
  95. }
  96. if state.layingChart ?? true {
  97. tirChart
  98. }
  99. }
  100. var body: some View {
  101. ZStack {
  102. VStack(alignment: .center) {
  103. chart().padding(.top, 20)
  104. Divider()
  105. stats()
  106. Divider()
  107. Picker("Duration", selection: $selectedDuration) {
  108. ForEach(Duration.allCases) { duration in
  109. Text(NSLocalizedString(duration.rawValue, comment: "")).tag(Optional(duration))
  110. }
  111. }
  112. .pickerStyle(.segmented)
  113. }
  114. }
  115. .onAppear(perform: configureView)
  116. .navigationBarTitle("Statistics")
  117. .navigationBarTitleDisplayMode(.automatic)
  118. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  119. }
  120. var loops: some View {
  121. VStack {
  122. let loops_ = loopStats(fetchedLoopStats)
  123. HStack {
  124. ForEach(0 ..< loops_.count, id: \.self) { index in
  125. VStack {
  126. Text(NSLocalizedString(loops_[index].string, comment: "")).font(.subheadline)
  127. .foregroundColor(.secondary)
  128. Text(
  129. index == 0 ? loops_[index].double.formatted() : (
  130. index == 2 ? loops_[index].double
  131. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(2))) :
  132. loops_[index]
  133. .double
  134. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))
  135. )
  136. )
  137. }.padding(.horizontal, 6)
  138. }
  139. }
  140. }
  141. }
  142. var hba1c: some View {
  143. let useUnit: GlucoseUnits = (state.units == .mmolL && (state.overrideUnit ?? false)) ? .mgdL :
  144. (state.units == .mgdL && (state.overrideUnit ?? false) || state.units == .mmolL) ? .mmolL : .mgdL
  145. return HStack {
  146. let hba1cs = glucoseStats(fetchedGlucose)
  147. let hba1cString = (
  148. useUnit == .mmolL ? hba1cs.ifcc
  149. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))) : hba1cs.ngsp
  150. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))
  151. + " %"
  152. )
  153. VStack {
  154. Text("HbA1C").font(.subheadline).foregroundColor(headline)
  155. HStack {
  156. VStack {
  157. Text(hba1cString)
  158. }
  159. }
  160. }.padding([.horizontal], 15)
  161. VStack {
  162. Text("SD").font(.subheadline).foregroundColor(.secondary)
  163. HStack {
  164. VStack {
  165. Text(
  166. hba1cs.sd
  167. .formatted(
  168. .number.grouping(.never).rounded()
  169. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  170. )
  171. )
  172. }
  173. }
  174. }.padding([.horizontal], 15)
  175. VStack {
  176. Text("CV").font(.subheadline).foregroundColor(.secondary)
  177. HStack {
  178. VStack {
  179. Text(
  180. hba1cs.cv.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))
  181. )
  182. }
  183. }
  184. }.padding([.horizontal], 15)
  185. // if selectedDuration == .Total || selectedDuration == .Today {
  186. VStack {
  187. Text("Days").font(.subheadline).foregroundColor(.secondary)
  188. HStack {
  189. VStack {
  190. Text(numberOfDays.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))))
  191. }
  192. }
  193. }.padding([.horizontal], 15)
  194. // }
  195. }
  196. }
  197. var bloodGlucose: some View {
  198. VStack {
  199. HStack {
  200. let bgs = glucoseStats(fetchedGlucose)
  201. VStack {
  202. HStack {
  203. Text(selectedDuration == .Today ? "Readings today" : "Readings / 24h").font(.subheadline)
  204. .foregroundColor(.secondary)
  205. }
  206. HStack {
  207. VStack {
  208. Text(
  209. bgs.readings.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))
  210. )
  211. }
  212. }
  213. }
  214. VStack {
  215. HStack {
  216. Text("Average").font(.subheadline).foregroundColor(headline)
  217. }
  218. HStack {
  219. VStack {
  220. Text(
  221. bgs.average
  222. .formatted(
  223. .number.grouping(.never).rounded()
  224. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  225. )
  226. )
  227. }
  228. }
  229. }
  230. VStack {
  231. HStack {
  232. Text("Median").font(.subheadline).foregroundColor(.secondary)
  233. }
  234. HStack {
  235. VStack {
  236. Text(
  237. bgs.median
  238. .formatted(
  239. .number.grouping(.never).rounded()
  240. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  241. )
  242. )
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }
  249. var numberOfDays: Double {
  250. let array = selectedDuration == .Today ? fetchedGlucoseDay : selectedDuration == .Day ?
  251. fetchedGlucoseTwentyFourHours :
  252. selectedDuration == .Week ? fetchedGlucoseWeek : selectedDuration == .Month ? fetchedGlucoseMonth :
  253. selectedDuration ==
  254. .Total ? fetchedGlucose : fetchedGlucoseDay
  255. let endIndex = array.count - 1
  256. var days = 0.0
  257. if endIndex > 0 {
  258. let firstElementTime = fetchedGlucose.first?.date ?? Date()
  259. let lastElementTime = fetchedGlucose[endIndex].date ?? Date()
  260. days = (firstElementTime - lastElementTime).timeInterval / 8.64E4
  261. }
  262. return days
  263. }
  264. var tirChart: some View {
  265. let array = selectedDuration == .Today ? fetchedGlucoseDay : selectedDuration == .Day ?
  266. fetchedGlucoseTwentyFourHours :
  267. selectedDuration == .Week ? fetchedGlucoseWeek : selectedDuration == .Month ? fetchedGlucoseMonth :
  268. selectedDuration ==
  269. .Total ? fetchedGlucose : fetchedGlucoseDay
  270. let fetched = tir(array)
  271. let data: [ShapeModel] = [
  272. .init(type: "Low", percent: fetched[0].decimal),
  273. .init(type: "In Range", percent: fetched[1].decimal),
  274. .init(type: "High", percent: fetched[2].decimal)
  275. ]
  276. return Chart(data) { shape in
  277. BarMark(
  278. x: .value("TIR", shape.percent)
  279. )
  280. .foregroundStyle(by: .value("Group", shape.type))
  281. .annotation(position: .overlay, alignment: .center) {
  282. Text(
  283. shape.percent == 0 ? "" : shape
  284. .percent < 12 ? "\(shape.percent, format: .number.precision(.fractionLength(0)))" :
  285. "\(shape.percent, format: .number.precision(.fractionLength(0))) %"
  286. )
  287. }
  288. }
  289. .chartXAxis(.hidden)
  290. .chartForegroundStyleScale(["Low": .red, "In Range": .green, "High": .orange]).frame(maxHeight: 55)
  291. }
  292. var standingTIRchart: some View {
  293. let array = selectedDuration == .Today ? fetchedGlucoseDay : selectedDuration == .Day ?
  294. fetchedGlucoseTwentyFourHours :
  295. selectedDuration == .Week ? fetchedGlucoseWeek : selectedDuration == .Month ? fetchedGlucoseMonth :
  296. selectedDuration == .Total ? fetchedGlucose : fetchedGlucoseDay
  297. let fetched = tir(array)
  298. let data: [ShapeModel] = [
  299. .init(type: "Low", percent: fetched[0].decimal),
  300. .init(type: "In Range", percent: fetched[1].decimal),
  301. .init(type: "High", percent: fetched[2].decimal)
  302. ]
  303. return VStack(alignment: .center) {
  304. Chart(data) { shape in
  305. BarMark(
  306. x: .value("Shape", shape.type),
  307. y: .value("Percentage", shape.percent)
  308. )
  309. .foregroundStyle(by: .value("Group", shape.type))
  310. .annotation(position: shape.percent < 5 ? .top : .overlay, alignment: .center) {
  311. Text(shape.percent == 0 ? "" : "\(shape.percent, format: .number.precision(.fractionLength(0))) %")
  312. }
  313. }
  314. .chartYAxis(.hidden)
  315. .chartLegend(.hidden)
  316. .chartForegroundStyleScale(["Low": .red, "In Range": .green, "High": .orange])
  317. }
  318. }
  319. var glucoseChart: some View {
  320. let count = fetchedGlucoseDay.count
  321. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  322. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  323. return Chart {
  324. ForEach(fetchedGlucoseDay.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  325. PointMark(
  326. x: .value("Date", item.date ?? Date()),
  327. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  328. )
  329. .foregroundStyle(.orange)
  330. .symbolSize(count < 20 ? 30 : 12)
  331. }
  332. ForEach(
  333. fetchedGlucoseDay
  334. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  335. id: \.date
  336. ) { item in
  337. PointMark(
  338. x: .value("Date", item.date ?? Date()),
  339. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  340. )
  341. .foregroundStyle(.green)
  342. .symbolSize(count < 20 ? 30 : 12)
  343. }
  344. ForEach(fetchedGlucoseDay.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  345. PointMark(
  346. x: .value("Date", item.date ?? Date()),
  347. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  348. )
  349. .foregroundStyle(.red)
  350. .symbolSize(count < 20 ? 30 : 12)
  351. }
  352. }
  353. .chartYAxis {
  354. AxisMarks(
  355. values: [
  356. 0,
  357. lowLimit,
  358. highLimit,
  359. state.units == .mmolL ? 15 : 270
  360. ]
  361. )
  362. }
  363. }
  364. var glucoseChartTwentyFourHours: some View {
  365. let count = fetchedGlucoseTwentyFourHours.count
  366. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  367. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  368. return Chart {
  369. ForEach(fetchedGlucoseTwentyFourHours.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  370. PointMark(
  371. x: .value("Date", item.date ?? Date()),
  372. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  373. )
  374. .foregroundStyle(.orange)
  375. .symbolSize(count < 20 ? 20 : 10)
  376. }
  377. ForEach(
  378. fetchedGlucoseTwentyFourHours
  379. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  380. id: \.date
  381. ) { item in
  382. PointMark(
  383. x: .value("Date", item.date ?? Date()),
  384. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  385. )
  386. .foregroundStyle(.green)
  387. .symbolSize(count < 20 ? 20 : 10)
  388. }
  389. ForEach(fetchedGlucoseTwentyFourHours.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  390. PointMark(
  391. x: .value("Date", item.date ?? Date()),
  392. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  393. )
  394. .foregroundStyle(.red)
  395. .symbolSize(count < 20 ? 20 : 10)
  396. }
  397. }
  398. .chartYAxis {
  399. AxisMarks(
  400. values: [
  401. 0,
  402. lowLimit,
  403. highLimit,
  404. state.units == .mmolL ? 15 : 270
  405. ]
  406. )
  407. } }
  408. var glucoseChartWeek: some View {
  409. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  410. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  411. return Chart {
  412. ForEach(fetchedGlucoseWeek.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  413. PointMark(
  414. x: .value("Date", item.date ?? Date()),
  415. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  416. )
  417. .foregroundStyle(.orange)
  418. .symbolSize(5)
  419. }
  420. ForEach(
  421. fetchedGlucoseWeek
  422. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  423. id: \.date
  424. ) { item in
  425. PointMark(
  426. x: .value("Date", item.date ?? Date()),
  427. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  428. )
  429. .foregroundStyle(.green)
  430. .symbolSize(5)
  431. }
  432. ForEach(fetchedGlucoseWeek.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  433. PointMark(
  434. x: .value("Date", item.date ?? Date()),
  435. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  436. )
  437. .foregroundStyle(.red)
  438. .symbolSize(5)
  439. }
  440. }
  441. .chartYAxis {
  442. AxisMarks(
  443. values: [
  444. 0,
  445. lowLimit,
  446. highLimit,
  447. state.units == .mmolL ? 15 : 270
  448. ]
  449. )
  450. }
  451. }
  452. var glucoseChartMonth: some View {
  453. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  454. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  455. return Chart {
  456. ForEach(fetchedGlucoseMonth.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  457. PointMark(
  458. x: .value("Date", item.date ?? Date()),
  459. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  460. )
  461. .foregroundStyle(.orange)
  462. .symbolSize(2)
  463. }
  464. ForEach(
  465. fetchedGlucoseMonth
  466. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  467. id: \.date
  468. ) { item in
  469. PointMark(
  470. x: .value("Date", item.date ?? Date()),
  471. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  472. )
  473. .foregroundStyle(.green)
  474. .symbolSize(2)
  475. }
  476. ForEach(fetchedGlucoseMonth.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  477. PointMark(
  478. x: .value("Date", item.date ?? Date()),
  479. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  480. )
  481. .foregroundStyle(.red)
  482. .symbolSize(2)
  483. }
  484. }
  485. .chartYAxis {
  486. AxisMarks(
  487. values: [
  488. 0,
  489. lowLimit,
  490. highLimit,
  491. state.units == .mmolL ? 15 : 270
  492. ]
  493. )
  494. }
  495. }
  496. var glucoseChart90: some View {
  497. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  498. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  499. return Chart {
  500. ForEach(fetchedGlucose.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  501. PointMark(
  502. x: .value("Date", item.date ?? Date()),
  503. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  504. )
  505. .foregroundStyle(.orange)
  506. .symbolSize(2)
  507. }
  508. ForEach(
  509. fetchedGlucose
  510. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  511. id: \.date
  512. ) { item in
  513. PointMark(
  514. x: .value("Date", item.date ?? Date()),
  515. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  516. )
  517. .foregroundStyle(.green)
  518. .symbolSize(2)
  519. }
  520. ForEach(fetchedGlucose.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  521. PointMark(
  522. x: .value("Date", item.date ?? Date()),
  523. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  524. )
  525. .foregroundStyle(.red)
  526. .symbolSize(2)
  527. }
  528. }
  529. .chartYAxis {
  530. AxisMarks(
  531. values: [
  532. 0,
  533. lowLimit,
  534. highLimit,
  535. state.units == .mmolL ? 15 : 270
  536. ]
  537. )
  538. }
  539. }
  540. private func loopStats(_ loops: FetchedResults<LoopStatRecord>) -> [(double: Double, string: String)] {
  541. guard (loops.first?.start) != nil else { return [] }
  542. var i = 0.0
  543. var minimumInt = 999.0
  544. var maximumInt = 0.0
  545. var timeIntervalLoops = 0.0
  546. var previousTimeLoop = loops.first?.end ?? Date()
  547. var timeIntervalLoopArray: [Double] = []
  548. let durationArray = loops.compactMap({ each in each.duration })
  549. let durationArrayCount = durationArray.count
  550. // var durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount)
  551. let medianDuration = medianCalculationDouble(array: durationArray)
  552. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  553. let errorNR = durationArrayCount - successsNR
  554. let successRate: Double? = (Double(successsNR) / Double(successsNR + errorNR)) * 100
  555. for each in loops {
  556. if let loopEnd = each.end {
  557. i += 1
  558. timeIntervalLoops = (previousTimeLoop - (each.start ?? previousTimeLoop)).timeInterval / 60
  559. if timeIntervalLoops > 0.0, i != 1 {
  560. timeIntervalLoopArray.append(timeIntervalLoops)
  561. }
  562. if timeIntervalLoops > maximumInt {
  563. maximumInt = timeIntervalLoops
  564. }
  565. if timeIntervalLoops < minimumInt, i != 1 {
  566. minimumInt = timeIntervalLoops
  567. }
  568. previousTimeLoop = loopEnd
  569. }
  570. }
  571. // Average Loop Interval in minutes
  572. let timeOfFirstIndex = loops.first?.start ?? Date()
  573. let lastIndexWithTimestamp = loops.count - 1
  574. let timeOfLastIndex = loops[lastIndexWithTimestamp].end ?? Date()
  575. let averageInterval = (timeOfFirstIndex - timeOfLastIndex).timeInterval / 60 / Double(errorNR + successsNR)
  576. if minimumInt == 999.0 {
  577. minimumInt = 0.0
  578. }
  579. var array: [(double: Double, string: String)] = []
  580. array.append((double: Double(successsNR + errorNR), string: "Loops"))
  581. array.append((double: averageInterval, string: "Interval"))
  582. array.append((double: medianDuration, string: "Duration"))
  583. array.append((double: successRate ?? 100, string: "%"))
  584. return array
  585. }
  586. private func medianCalculation(array: [Int]) -> Double {
  587. guard !array.isEmpty else {
  588. return 0
  589. }
  590. let sorted = array.sorted()
  591. let length = array.count
  592. if length % 2 == 0 {
  593. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  594. }
  595. return Double(sorted[length / 2])
  596. }
  597. private func medianCalculationDouble(array: [Double]) -> Double {
  598. guard !array.isEmpty else {
  599. return 0
  600. }
  601. let sorted = array.sorted()
  602. let length = array.count
  603. if length % 2 == 0 {
  604. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  605. }
  606. return sorted[length / 2]
  607. }
  608. private func glucoseStats(_ glucose_90: FetchedResults<Readings>)
  609. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  610. {
  611. var numberOfDays: Double = 0
  612. let endIndex = glucose_90.count - 1
  613. if endIndex > 0 {
  614. let firstElementTime = glucose_90[0].date ?? Date()
  615. let lastElementTime = glucose_90[endIndex].date ?? Date()
  616. numberOfDays = (firstElementTime - lastElementTime).timeInterval / 8.64E4
  617. }
  618. var duration = 1
  619. var denominator: Double = 1
  620. switch selectedDuration {
  621. case .Today:
  622. let minutesSinceMidnight = Calendar.current.component(.hour, from: Date()) * 60 + Calendar.current
  623. .component(.minute, from: Date())
  624. duration = minutesSinceMidnight
  625. denominator = 1
  626. case .Day:
  627. duration = 1 * 1440
  628. denominator = 1
  629. case .Week:
  630. duration = 7 * 1440
  631. if numberOfDays > 7 { denominator = 7 } else { denominator = numberOfDays }
  632. case .Month:
  633. duration = 30 * 1440
  634. if numberOfDays > 30 { denominator = 30 } else { denominator = numberOfDays }
  635. case .Total:
  636. duration = 90 * 1440
  637. if numberOfDays >= 90 { denominator = 90 } else { denominator = numberOfDays }
  638. }
  639. let timeAgo = Date().addingTimeInterval(-duration.minutes.timeInterval)
  640. let glucose = glucose_90.filter({ ($0.date ?? Date()) >= timeAgo })
  641. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  642. let sumReadings = justGlucoseArray.reduce(0, +)
  643. let countReadings = justGlucoseArray.count
  644. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  645. let medianGlucose = medianCalculation(array: justGlucoseArray)
  646. var NGSPa1CStatisticValue = 0.0
  647. var IFCCa1CStatisticValue = 0.0
  648. if numberOfDays > 0 {
  649. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  650. IFCCa1CStatisticValue = 10.929 *
  651. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  652. }
  653. var sumOfSquares = 0.0
  654. for array in justGlucoseArray {
  655. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  656. }
  657. var sd = 0.0
  658. var cv = 0.0
  659. // Avoid division by zero
  660. if glucoseAverage > 0 {
  661. sd = sqrt(sumOfSquares / Double(countReadings))
  662. cv = sd / Double(glucoseAverage) * 100
  663. }
  664. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  665. output = (
  666. ifcc: IFCCa1CStatisticValue,
  667. ngsp: NGSPa1CStatisticValue,
  668. average: glucoseAverage * (state.units == .mmolL ? conversionFactor : 1),
  669. median: medianGlucose * (state.units == .mmolL ? conversionFactor : 1),
  670. sd: sd * (state.units == .mmolL ? conversionFactor : 1), cv: cv,
  671. readings: Double(countReadings) / denominator
  672. )
  673. return output
  674. }
  675. private func tir(_ glucose_90: FetchedResults<Readings>) -> [(decimal: Decimal, string: String)] {
  676. var duration = 1
  677. switch selectedDuration {
  678. case .Today:
  679. let minutesSinceMidnight = Calendar.current.component(.hour, from: Date()) * 60 + Calendar.current
  680. .component(.minute, from: Date())
  681. duration = minutesSinceMidnight
  682. case .Day:
  683. duration = 1 * 1440
  684. case .Week:
  685. duration = 7 * 1440
  686. case .Month:
  687. duration = 30 * 1440
  688. case .Total:
  689. duration = 90 * 1440
  690. }
  691. let hypoLimit = Int(state.lowLimit ?? 70)
  692. let hyperLimit = Int(state.highLimit ?? 145)
  693. let timeAgo = Date().addingTimeInterval(-duration.minutes.timeInterval)
  694. let glucose = glucose_90.filter({ ($0.date ?? Date()) >= timeAgo })
  695. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  696. let totalReadings = justGlucoseArray.count
  697. let hyperArray = glucose.filter({ $0.glucose >= hyperLimit })
  698. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  699. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  700. let hypoArray = glucose.filter({ $0.glucose <= hypoLimit })
  701. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  702. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  703. let tir = 100 - (hypoPercentage + hyperPercentage)
  704. var array: [(decimal: Decimal, string: String)] = []
  705. array.append((decimal: Decimal(hypoPercentage), string: "Low"))
  706. array.append((decimal: Decimal(tir), string: "NormaL"))
  707. array.append((decimal: Decimal(hyperPercentage), string: "High"))
  708. return array
  709. }
  710. private func colorOfGlucose(_ index: Int) -> Color {
  711. let whichIndex = index
  712. switch whichIndex {
  713. case 0:
  714. return .red
  715. case 1:
  716. return .green
  717. case 2:
  718. return .orange
  719. default:
  720. return .primary
  721. }
  722. }
  723. }
  724. }