OverrideProfilesRootView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. Spacer()
  66. Text("\(state.percentage.formatted(.number)) %")
  67. .foregroundColor(
  68. state
  69. .percentage >= 130 ? .red :
  70. (isEditing ? .orange : .blue)
  71. )
  72. .font(.largeTitle)
  73. Slider(
  74. value: $state.percentage,
  75. in: 10 ... 200,
  76. step: 1,
  77. onEditingChanged: { editing in
  78. isEditing = editing
  79. }
  80. ).accentColor(state.percentage >= 130 ? .red : .blue)
  81. Spacer()
  82. Toggle(isOn: $state._indefinite) {
  83. Text("Enable indefinitely")
  84. }
  85. }
  86. if !state._indefinite {
  87. HStack {
  88. Text("Duration")
  89. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: false)
  90. Text("minutes").foregroundColor(.secondary)
  91. }
  92. }
  93. HStack {
  94. Toggle(isOn: $state.override_target) {
  95. Text("Override Profile Target")
  96. }
  97. }
  98. if state.override_target {
  99. HStack {
  100. Text("Target Glucose")
  101. DecimalTextField("0", value: $state.target, formatter: glucoseFormatter, cleanInput: false)
  102. Text(state.units.rawValue).foregroundColor(.secondary)
  103. }
  104. }
  105. HStack {
  106. Toggle(isOn: $state.advancedSettings) {
  107. Text("More options")
  108. }
  109. }
  110. if state.advancedSettings {
  111. HStack {
  112. Toggle(isOn: $state.smbIsOff) {
  113. Text("Disable SMBs")
  114. }
  115. }
  116. HStack {
  117. Toggle(isOn: $state.smbIsAlwaysOff) {
  118. Text("Schedule when SMBs are Off")
  119. }.disabled(!state.smbIsOff)
  120. }
  121. if state.smbIsAlwaysOff {
  122. HStack {
  123. Text("First Hour SMBs are Off (24 hours)")
  124. DecimalTextField("0", value: $state.start, formatter: formatter, cleanInput: false)
  125. Text("hour").foregroundColor(.secondary)
  126. }
  127. HStack {
  128. Text("Last Hour SMBs are Off (24 hours)")
  129. DecimalTextField("0", value: $state.end, formatter: formatter, cleanInput: false)
  130. Text("hour").foregroundColor(.secondary)
  131. }
  132. }
  133. HStack {
  134. Toggle(isOn: $state.isfAndCr) {
  135. Text("Change ISF and CR")
  136. }
  137. }
  138. if !state.isfAndCr {
  139. HStack {
  140. Toggle(isOn: $state.isf) {
  141. Text("Change ISF")
  142. }
  143. }
  144. HStack {
  145. Toggle(isOn: $state.cr) {
  146. Text("Change CR")
  147. }
  148. }
  149. }
  150. HStack {
  151. Text("SMB Minutes")
  152. DecimalTextField(
  153. "0",
  154. value: $state.smbMinutes,
  155. formatter: formatter,
  156. cleanInput: false
  157. )
  158. Text("minutes").foregroundColor(.secondary)
  159. }
  160. HStack {
  161. Text("UAM SMB Minutes")
  162. DecimalTextField(
  163. "0",
  164. value: $state.uamMinutes,
  165. formatter: formatter,
  166. cleanInput: false
  167. )
  168. Text("minutes").foregroundColor(.secondary)
  169. }
  170. }
  171. HStack {
  172. Button("Start new Profile") {
  173. showAlert.toggle()
  174. alertSring = "\(state.percentage.formatted(.number)) %, " +
  175. (
  176. state.duration > 0 || !state
  177. ._indefinite ?
  178. (
  179. state
  180. .duration
  181. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  182. " min."
  183. ) :
  184. NSLocalizedString(" infinite duration.", comment: "")
  185. ) +
  186. (
  187. (state.target == 0 || !state.override_target) ? "" :
  188. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  189. )
  190. +
  191. (
  192. state
  193. .smbIsOff ?
  194. NSLocalizedString(
  195. " SMBs are disabled either by schedule or during the entire duration.",
  196. comment: ""
  197. ) : ""
  198. )
  199. +
  200. "\n\n"
  201. +
  202. NSLocalizedString(
  203. "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.",
  204. comment: ""
  205. )
  206. }
  207. .disabled(unChanged())
  208. .buttonStyle(BorderlessButtonStyle())
  209. .font(.callout)
  210. .controlSize(.mini)
  211. .alert(
  212. "Start Profile",
  213. isPresented: $showAlert,
  214. actions: {
  215. Button("Cancel", role: .cancel) { state.isEnabled = false }
  216. Button("Start Profile", role: .destructive) {
  217. if state._indefinite { state.duration = 0 }
  218. state.isEnabled.toggle()
  219. state.saveSettings()
  220. dismiss()
  221. }
  222. },
  223. message: {
  224. Text(alertSring)
  225. }
  226. )
  227. Button {
  228. isSheetPresented = true
  229. }
  230. label: { Text("Save as Profile") }
  231. .tint(.orange)
  232. .frame(maxWidth: .infinity, alignment: .trailing)
  233. .buttonStyle(BorderlessButtonStyle())
  234. .controlSize(.mini)
  235. .disabled(unChanged())
  236. }
  237. .sheet(isPresented: $isSheetPresented) {
  238. presetPopover
  239. }
  240. }
  241. header: {
  242. HStack {
  243. Text("Insulin")
  244. Spacer()
  245. Button {
  246. state.showModal(for: .addTempTarget)
  247. } label: {
  248. HStack {
  249. Image(systemName: "plus.circle.fill")
  250. .font(.system(size: 20))
  251. Text("add temp target")
  252. .font(.caption)
  253. .foregroundStyle(Color.blue)
  254. }
  255. }
  256. }
  257. }
  258. footer: {
  259. Text(
  260. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  261. )
  262. }
  263. Button("Return to Normal") {
  264. state.cancelProfile()
  265. dismiss()
  266. }
  267. .frame(maxWidth: .infinity, alignment: .center)
  268. .buttonStyle(BorderlessButtonStyle())
  269. .disabled(!state.isEnabled)
  270. .tint(.red)
  271. }
  272. .onAppear(perform: configureView)
  273. .onAppear { state.savedSettings() }
  274. .navigationBarTitle("Profiles")
  275. .navigationBarTitleDisplayMode(.automatic)
  276. .navigationBarItems(trailing: Button("Close", action: state.hideModal))
  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. }