OverrideProfilesRootView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. @FetchRequest(
  17. entity: OverridePresets.entity(),
  18. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  19. format: "name != %@", "" as String
  20. )
  21. ) var fetchedProfiles: FetchedResults<OverridePresets>
  22. private var formatter: NumberFormatter {
  23. let formatter = NumberFormatter()
  24. formatter.numberStyle = .decimal
  25. formatter.maximumFractionDigits = 0
  26. return formatter
  27. }
  28. private var glucoseFormatter: NumberFormatter {
  29. let formatter = NumberFormatter()
  30. formatter.numberStyle = .decimal
  31. formatter.maximumFractionDigits = 0
  32. if state.units == .mmolL {
  33. formatter.maximumFractionDigits = 1
  34. }
  35. formatter.roundingMode = .halfUp
  36. return formatter
  37. }
  38. private var color: LinearGradient {
  39. colorScheme == .dark ? LinearGradient(
  40. gradient: Gradient(colors: [
  41. // RGB(10, 34, 55)
  42. Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745),
  43. // RGB(3, 15, 28)
  44. Color(red: 0.011, green: 0.058, blue: 0.109),
  45. // RGB(10, 34, 55)
  46. Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745)
  47. ]),
  48. startPoint: .top,
  49. endPoint: .bottom
  50. )
  51. :
  52. LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.1)]), startPoint: .top, endPoint: .bottom)
  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 : .blue)
  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. ).accentColor(state.percentage >= 130 ? .red : .blue)
  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: {
  259. HStack {
  260. Text("Insulin")
  261. Spacer()
  262. Button {
  263. state.showModal(for: .addTempTarget)
  264. } label: {
  265. HStack {
  266. Image(systemName: "plus.circle.fill")
  267. .font(.system(size: 20))
  268. Text("add temp target")
  269. .font(.caption)
  270. .foregroundStyle(Color.blue)
  271. }
  272. }
  273. }
  274. }
  275. footer: {
  276. Text(
  277. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  278. )
  279. }
  280. Button("Return to Normal") {
  281. state.cancelProfile()
  282. dismiss()
  283. }
  284. .frame(maxWidth: .infinity, alignment: .center)
  285. .buttonStyle(BorderlessButtonStyle())
  286. .disabled(!state.isEnabled)
  287. .tint(.red)
  288. }.scrollContentBackground(.hidden).background(color)
  289. .onAppear(perform: configureView)
  290. .onAppear { state.savedSettings() }
  291. .navigationBarTitle("Profiles")
  292. .navigationBarTitleDisplayMode(.automatic)
  293. .navigationBarItems(trailing: Button("Close", action: state.hideModal))
  294. }
  295. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  296. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  297. .asMmolL : (preset.target ?? 0) as Decimal
  298. let duration = (preset.duration ?? 0) as Decimal
  299. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  300. let percent = preset.percentage / 100
  301. let perpetual = preset.indefinite
  302. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  303. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsAlwaysOff) ? "Scheduled SMBs" : ""
  304. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  305. let targetString = target != 0 ? "\(glucoseFormatter.string(from: target as NSNumber)!)" : ""
  306. let maxMinutesSMB = (preset.smbMinutes as Decimal?) != nil ? (preset.smbMinutes ?? 0) as Decimal : 0
  307. let maxMinutesUAM = (preset.uamMinutes as Decimal?) != nil ? (preset.uamMinutes ?? 0) as Decimal : 0
  308. let isfString = preset.isf ? "ISF" : ""
  309. let crString = preset.cr ? "CR" : ""
  310. let dash = crString != "" ? "/" : ""
  311. let isfAndCRstring = isfString + dash + crString
  312. if name != "" {
  313. HStack {
  314. VStack {
  315. HStack {
  316. Text(name)
  317. Spacer()
  318. }
  319. HStack(spacing: 5) {
  320. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  321. if targetString != "" {
  322. Text(targetString)
  323. Text(targetString != "" ? state.units.rawValue : "")
  324. }
  325. if durationString != "" { Text(durationString + (perpetual ? "" : "min")) }
  326. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  327. if scheduledSMBstring != "" { Text(scheduledSMBstring) }
  328. if preset.advancedSettings {
  329. Text(maxMinutesSMB == 0 ? "" : maxMinutesSMB.formatted() + " SMB")
  330. Text(maxMinutesUAM == 0 ? "" : maxMinutesUAM.formatted() + " UAM")
  331. Text(isfAndCRstring)
  332. }
  333. Spacer()
  334. }
  335. .padding(.top, 2)
  336. .foregroundColor(.secondary)
  337. .font(.caption)
  338. }
  339. .contentShape(Rectangle())
  340. .onTapGesture {
  341. state.selectProfile(id_: preset.id ?? "")
  342. state.hideModal()
  343. }
  344. }
  345. }
  346. }
  347. private func unChanged() -> Bool {
  348. let isChanged = (state.percentage == 100 && !state.override_target && !state.smbIsOff && !state.advancedSettings) ||
  349. (!state._indefinite && state.duration == 0) || (state.override_target && state.target == 0) ||
  350. (
  351. state.percentage == 100 && !state.override_target && !state.smbIsOff && state.isf && state.cr && state
  352. .smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  353. )
  354. return isChanged
  355. }
  356. private func removeProfile(at offsets: IndexSet) {
  357. for index in offsets {
  358. let language = fetchedProfiles[index]
  359. moc.delete(language)
  360. }
  361. do {
  362. try moc.save()
  363. } catch {
  364. // To do: add error
  365. }
  366. }
  367. }
  368. }