OverrideProfilesRootView.swift 17 KB

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