OverrideProfilesRootView.swift 17 KB

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