OverrideProfilesRootView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. @Environment(\.dismiss) var dismiss
  13. @Environment(\.managedObjectContext) var moc
  14. @FetchRequest(
  15. entity: OverridePresets.entity(),
  16. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  17. format: "name != %@", "" as String
  18. )
  19. ) var fetchedProfiles: FetchedResults<OverridePresets>
  20. private var formatter: NumberFormatter {
  21. let formatter = NumberFormatter()
  22. formatter.numberStyle = .decimal
  23. formatter.maximumFractionDigits = 0
  24. return formatter
  25. }
  26. private var glucoseFormatter: NumberFormatter {
  27. let formatter = NumberFormatter()
  28. formatter.numberStyle = .decimal
  29. formatter.maximumFractionDigits = 0
  30. if state.units == .mmolL {
  31. formatter.maximumFractionDigits = 1
  32. }
  33. formatter.roundingMode = .halfUp
  34. return formatter
  35. }
  36. var presetPopover: some View {
  37. Form {
  38. Section(header: Text("Enter Profile Name")) {
  39. TextField("Name Of Profile", text: $state.profileName)
  40. Button {
  41. state.savePreset()
  42. }
  43. label: { Text("Save") }
  44. .disabled(
  45. state.profileName == "" ||
  46. fetchedProfiles.filter({ $0.name == state.profileName }).isNotEmpty
  47. )
  48. Button {
  49. state.isPromtPresented = false }
  50. label: { Text("Cancel") }
  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. let minutes = state.settingsManager.preferences.maxSMBBasalMinutes
  152. DecimalTextField(
  153. minutes.formatted(),
  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. let uam_minutes = state.settingsManager.preferences.maxUAMSMBBasalMinutes
  163. DecimalTextField(
  164. uam_minutes.formatted(),
  165. value: $state.uamMinutes,
  166. formatter: formatter,
  167. cleanInput: false
  168. )
  169. Text("minutes").foregroundColor(.secondary)
  170. }
  171. }
  172. HStack {
  173. Button("Start new Profile") {
  174. showAlert.toggle()
  175. alertSring = "\(state.percentage.formatted(.number)) %, " +
  176. (
  177. state.duration > 0 || !state
  178. ._indefinite ?
  179. (
  180. state
  181. .duration
  182. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  183. " min."
  184. ) :
  185. NSLocalizedString(" infinite duration.", comment: "")
  186. ) +
  187. (
  188. (state.target == 0 || !state.override_target) ? "" :
  189. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  190. )
  191. +
  192. (
  193. state
  194. .smbIsOff ?
  195. NSLocalizedString(
  196. " SMBs are disabled either by schedule or during the entire duration.",
  197. comment: ""
  198. ) : ""
  199. )
  200. +
  201. "\n\n"
  202. +
  203. NSLocalizedString(
  204. "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.",
  205. comment: ""
  206. )
  207. }
  208. .disabled(
  209. (state.percentage == 100 && !state.override_target && !state.smbIsOff) ||
  210. (!state._indefinite && state.duration == 0) || (state.override_target && state.target == 0)
  211. )
  212. // .tint(.blue)
  213. .buttonStyle(BorderlessButtonStyle())
  214. .font(.callout)
  215. .controlSize(.mini)
  216. .alert(
  217. "Start Profile",
  218. isPresented: $showAlert,
  219. actions: {
  220. Button("Cancel", role: .cancel) { state.isEnabled = false }
  221. Button("Start Profile", role: .destructive) {
  222. if state._indefinite { state.duration = 0 }
  223. state.isEnabled.toggle()
  224. state.saveSettings()
  225. dismiss()
  226. }
  227. },
  228. message: {
  229. Text(alertSring)
  230. }
  231. )
  232. Button {
  233. state.isPromtPresented.toggle()
  234. }
  235. label: { Text("Save as Profile") }
  236. .tint(.orange)
  237. .frame(maxWidth: .infinity, alignment: .trailing)
  238. .buttonStyle(BorderlessButtonStyle())
  239. .controlSize(.mini)
  240. .disabled(
  241. (state.percentage == 100 && !state.override_target && !state.smbIsOff) ||
  242. (!state._indefinite && state.duration == 0) || (state.override_target && state.target == 0)
  243. )
  244. }
  245. .popover(isPresented: $state.isPromtPresented) {
  246. presetPopover
  247. }
  248. }
  249. header: { Text("Insulin") }
  250. footer: {
  251. Text(
  252. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  253. )
  254. }
  255. Button("Return to Normal") {
  256. state.cancelProfile()
  257. dismiss()
  258. }
  259. .frame(maxWidth: .infinity, alignment: .center)
  260. .buttonStyle(BorderlessButtonStyle())
  261. .disabled(!state.isEnabled)
  262. .tint(.red)
  263. }
  264. .onAppear(perform: configureView)
  265. .onAppear { state.savedSettings() }
  266. .navigationBarTitle("Profiles")
  267. .navigationBarTitleDisplayMode(.automatic)
  268. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  269. }
  270. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  271. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  272. .asMmolL : (preset.target ?? 0) as Decimal
  273. let duration = (preset.duration ?? 0) as Decimal
  274. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  275. let percent = preset.percentage / 100
  276. let perpetual = preset.indefinite
  277. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  278. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsAlwaysOff) ? "Scheduled SMBs" : ""
  279. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  280. let targetString = target != 0 ? "\(formatter.string(from: target as NSNumber)!)" : ""
  281. if name != "" {
  282. HStack {
  283. VStack {
  284. HStack {
  285. Text(name)
  286. Spacer()
  287. }
  288. HStack(spacing: 5) {
  289. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  290. .foregroundColor(.secondary)
  291. .font(.caption)
  292. if targetString != "" {
  293. Text(targetString)
  294. .foregroundColor(.secondary)
  295. .font(.caption)
  296. Text(targetString != "" ? state.units.rawValue : "")
  297. .foregroundColor(.secondary)
  298. .font(.caption) }
  299. if durationString != "" {
  300. Text(durationString + (perpetual ? "" : "min"))
  301. .foregroundColor(.secondary)
  302. .font(.caption) }
  303. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  304. Text(scheduledSMBstring)
  305. .foregroundColor(.secondary)
  306. .font(.caption)
  307. Spacer()
  308. }.padding(.top, 2)
  309. }
  310. .contentShape(Rectangle())
  311. .onTapGesture {
  312. state.selectProfile(id_: preset.id ?? "")
  313. state.hideModal()
  314. }
  315. }
  316. }
  317. }
  318. private func removeProfile(at offsets: IndexSet) {
  319. for index in offsets {
  320. let language = fetchedProfiles[index]
  321. moc.delete(language)
  322. }
  323. do {
  324. try moc.save()
  325. } catch {
  326. // To do: add error
  327. }
  328. }
  329. }
  330. }