OverrideProfilesRootView.swift 17 KB

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