OverrideProfilesRootView.swift 16 KB

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