StatRootView.swift 34 KB

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