OverrideProfilesRootView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension OverrideProfilesConfig {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @StateObject var state = StateModel()
  8. @State private var isEditing = false
  9. @State private var showAlert = false
  10. @State private var showingDetail = false
  11. @State private var alertSring = ""
  12. @State var isSheetPresented: Bool = false
  13. @Environment(\.dismiss) var dismiss
  14. @Environment(\.managedObjectContext) var moc
  15. @Environment(\.colorScheme) var colorScheme
  16. var color: LinearGradient {
  17. colorScheme == .dark ? LinearGradient(
  18. gradient: Gradient(colors: [
  19. Color.bgDarkBlue,
  20. Color.bgDarkerDarkBlue
  21. ]),
  22. startPoint: .top,
  23. endPoint: .bottom
  24. )
  25. :
  26. LinearGradient(
  27. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  28. startPoint: .top,
  29. endPoint: .bottom
  30. )
  31. }
  32. @FetchRequest(
  33. entity: OverridePresets.entity(),
  34. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  35. format: "name != %@", "" as String
  36. )
  37. ) var fetchedProfiles: FetchedResults<OverridePresets>
  38. private var formatter: NumberFormatter {
  39. let formatter = NumberFormatter()
  40. formatter.numberStyle = .decimal
  41. formatter.maximumFractionDigits = 0
  42. return formatter
  43. }
  44. private var glucoseFormatter: NumberFormatter {
  45. let formatter = NumberFormatter()
  46. formatter.numberStyle = .decimal
  47. formatter.maximumFractionDigits = 0
  48. if state.units == .mmolL {
  49. formatter.maximumFractionDigits = 1
  50. }
  51. formatter.roundingMode = .halfUp
  52. return formatter
  53. }
  54. var presetPopover: some View {
  55. Form {
  56. Section {
  57. TextField("Name Of Profile", text: $state.profileName)
  58. } header: { Text("Enter Name of Profile") }
  59. Section {
  60. Button("Save") {
  61. state.savePreset()
  62. isSheetPresented = false
  63. }
  64. .disabled(state.profileName.isEmpty || fetchedProfiles.filter({ $0.name == state.profileName }).isNotEmpty)
  65. Button("Cancel") {
  66. isSheetPresented = false
  67. }
  68. }
  69. }
  70. }
  71. var body: some View {
  72. Form {
  73. if state.presets.isNotEmpty {
  74. Section {
  75. ForEach(fetchedProfiles) { preset in
  76. profilesView(for: preset)
  77. }.onDelete(perform: removeProfile)
  78. }
  79. }
  80. Section {
  81. VStack {
  82. Spacer()
  83. Text("\(state.percentage.formatted(.number)) %")
  84. .foregroundColor(
  85. state
  86. .percentage >= 130 ? .red :
  87. (isEditing ? .orange : Color.tapBar)
  88. )
  89. .font(.largeTitle)
  90. Slider(
  91. value: $state.percentage,
  92. in: 10 ... 200,
  93. step: 1,
  94. onEditingChanged: { editing in
  95. isEditing = editing
  96. }
  97. )
  98. Spacer()
  99. Toggle(isOn: $state._indefinite) {
  100. Text("Enable indefinitely")
  101. }
  102. }
  103. if !state._indefinite {
  104. HStack {
  105. Text("Duration")
  106. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: false)
  107. Text("minutes").foregroundColor(.secondary)
  108. }
  109. }
  110. HStack {
  111. Toggle(isOn: $state.override_target) {
  112. Text("Override Profile Target")
  113. }
  114. }
  115. if state.override_target {
  116. HStack {
  117. Text("Target Glucose")
  118. DecimalTextField("0", value: $state.target, formatter: glucoseFormatter, cleanInput: false)
  119. Text(state.units.rawValue).foregroundColor(.secondary)
  120. }
  121. }
  122. HStack {
  123. Toggle(isOn: $state.advancedSettings) {
  124. Text("More options")
  125. }
  126. }
  127. if state.advancedSettings {
  128. HStack {
  129. Toggle(isOn: $state.smbIsOff) {
  130. Text("Disable SMBs")
  131. }
  132. }
  133. HStack {
  134. Toggle(isOn: $state.smbIsAlwaysOff) {
  135. Text("Schedule when SMBs are Off")
  136. }.disabled(!state.smbIsOff)
  137. }
  138. if state.smbIsAlwaysOff {
  139. HStack {
  140. Text("First Hour SMBs are Off (24 hours)")
  141. DecimalTextField("0", value: $state.start, formatter: formatter, cleanInput: false)
  142. Text("hour").foregroundColor(.secondary)
  143. }
  144. HStack {
  145. Text("Last Hour SMBs are Off (24 hours)")
  146. DecimalTextField("0", value: $state.end, formatter: formatter, cleanInput: false)
  147. Text("hour").foregroundColor(.secondary)
  148. }
  149. }
  150. HStack {
  151. Toggle(isOn: $state.isfAndCr) {
  152. Text("Change ISF and CR")
  153. }
  154. }
  155. if !state.isfAndCr {
  156. HStack {
  157. Toggle(isOn: $state.isf) {
  158. Text("Change ISF")
  159. }
  160. }
  161. HStack {
  162. Toggle(isOn: $state.cr) {
  163. Text("Change CR")
  164. }
  165. }
  166. }
  167. HStack {
  168. Text("SMB Minutes")
  169. DecimalTextField(
  170. "0",
  171. value: $state.smbMinutes,
  172. formatter: formatter,
  173. cleanInput: false
  174. )
  175. Text("minutes").foregroundColor(.secondary)
  176. }
  177. HStack {
  178. Text("UAM SMB Minutes")
  179. DecimalTextField(
  180. "0",
  181. value: $state.uamMinutes,
  182. formatter: formatter,
  183. cleanInput: false
  184. )
  185. Text("minutes").foregroundColor(.secondary)
  186. }
  187. }
  188. HStack {
  189. Button("Start new Profile") {
  190. showAlert.toggle()
  191. alertSring = "\(state.percentage.formatted(.number)) %, " +
  192. (
  193. state.duration > 0 || !state
  194. ._indefinite ?
  195. (
  196. state
  197. .duration
  198. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  199. " min."
  200. ) :
  201. NSLocalizedString(" infinite duration.", comment: "")
  202. ) +
  203. (
  204. (state.target == 0 || !state.override_target) ? "" :
  205. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  206. )
  207. +
  208. (
  209. state
  210. .smbIsOff ?
  211. NSLocalizedString(
  212. " SMBs are disabled either by schedule or during the entire duration.",
  213. comment: ""
  214. ) : ""
  215. )
  216. +
  217. "\n\n"
  218. +
  219. NSLocalizedString(
  220. "Starting this override will change your Profiles and/or your Target Glucose used for looping during the entire selected duration. Tapping ”Start Profile” will start your new profile or edit your current active profile.",
  221. comment: ""
  222. )
  223. }
  224. .disabled(unChanged())
  225. .buttonStyle(BorderlessButtonStyle())
  226. .font(.callout)
  227. .controlSize(.mini)
  228. .alert(
  229. "Start Profile",
  230. isPresented: $showAlert,
  231. actions: {
  232. Button("Cancel", role: .cancel) { state.isEnabled = false }
  233. Button("Start Profile", role: .destructive) {
  234. if state._indefinite { state.duration = 0 }
  235. state.isEnabled.toggle()
  236. state.saveSettings()
  237. dismiss()
  238. }
  239. },
  240. message: {
  241. Text(alertSring)
  242. }
  243. )
  244. Button {
  245. isSheetPresented = true
  246. }
  247. label: { Text("Save as Profile") }
  248. .tint(.orange)
  249. .frame(maxWidth: .infinity, alignment: .trailing)
  250. .buttonStyle(BorderlessButtonStyle())
  251. .controlSize(.mini)
  252. .disabled(unChanged())
  253. }
  254. .sheet(isPresented: $isSheetPresented) {
  255. presetPopover
  256. }
  257. }
  258. header: { Text("Insulin") }
  259. footer: {
  260. Text(
  261. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  262. )
  263. }.listRowBackground(colorScheme == .dark ? Color.chart : Color.white)
  264. Button("Return to Normal") {
  265. state.cancelProfile()
  266. dismiss()
  267. }.listRowBackground(colorScheme == .dark ? Color.chart : Color.white)
  268. .frame(maxWidth: .infinity, alignment: .center)
  269. .buttonStyle(BorderlessButtonStyle())
  270. .disabled(!state.isEnabled)
  271. .tint(.red)
  272. }.scrollContentBackground(.hidden).background(color)
  273. .onAppear(perform: configureView)
  274. .onAppear { state.savedSettings() }
  275. .navigationBarTitle("Profiles")
  276. .navigationBarTitleDisplayMode(.inline)
  277. }
  278. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  279. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  280. .asMmolL : (preset.target ?? 0) as Decimal
  281. let duration = (preset.duration ?? 0) as Decimal
  282. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  283. let percent = preset.percentage / 100
  284. let perpetual = preset.indefinite
  285. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  286. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsAlwaysOff) ? "Scheduled SMBs" : ""
  287. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  288. let targetString = target != 0 ? "\(glucoseFormatter.string(from: target as NSNumber)!)" : ""
  289. let maxMinutesSMB = (preset.smbMinutes as Decimal?) != nil ? (preset.smbMinutes ?? 0) as Decimal : 0
  290. let maxMinutesUAM = (preset.uamMinutes as Decimal?) != nil ? (preset.uamMinutes ?? 0) as Decimal : 0
  291. let isfString = preset.isf ? "ISF" : ""
  292. let crString = preset.cr ? "CR" : ""
  293. let dash = crString != "" ? "/" : ""
  294. let isfAndCRstring = isfString + dash + crString
  295. if name != "" {
  296. HStack {
  297. VStack {
  298. HStack {
  299. Text(name)
  300. Spacer()
  301. }
  302. HStack(spacing: 5) {
  303. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  304. if targetString != "" {
  305. Text(targetString)
  306. Text(targetString != "" ? state.units.rawValue : "")
  307. }
  308. if durationString != "" { Text(durationString + (perpetual ? "" : "min")) }
  309. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  310. if scheduledSMBstring != "" { Text(scheduledSMBstring) }
  311. if preset.advancedSettings {
  312. Text(maxMinutesSMB == 0 ? "" : maxMinutesSMB.formatted() + " SMB")
  313. Text(maxMinutesUAM == 0 ? "" : maxMinutesUAM.formatted() + " UAM")
  314. Text(isfAndCRstring)
  315. }
  316. Spacer()
  317. }
  318. .padding(.top, 2)
  319. .foregroundColor(.secondary)
  320. .font(.caption)
  321. }
  322. .contentShape(Rectangle())
  323. .onTapGesture {
  324. state.selectProfile(id_: preset.id ?? "")
  325. state.hideModal()
  326. }
  327. }
  328. }
  329. }
  330. private func unChanged() -> Bool {
  331. let isChanged = (state.percentage == 100 && !state.override_target && !state.smbIsOff && !state.advancedSettings) ||
  332. (!state._indefinite && state.duration == 0) || (state.override_target && state.target == 0) ||
  333. (
  334. state.percentage == 100 && !state.override_target && !state.smbIsOff && state.isf && state.cr && state
  335. .smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  336. )
  337. return isChanged
  338. }
  339. private func removeProfile(at offsets: IndexSet) {
  340. for index in offsets {
  341. let language = fetchedProfiles[index]
  342. moc.delete(language)
  343. }
  344. do {
  345. try moc.save()
  346. } catch {
  347. // To do: add error
  348. }
  349. }
  350. }
  351. }