Screaming-Reminder/Screaming Reminder/Views/SheetView.swift

97 lines
2.9 KiB
Swift
Raw Normal View History

2024-07-11 10:38:11 +00:00
//
// SheetView.swift
// Screaming Reminder
//
// Created by Amine Bou on 20/07/2024.
//
import SwiftUI
import SwiftData
struct SheetView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.modelContext) private var modelContext
@Binding var selectedLabel: String
@Binding var selectedReminder: Reminder?
@Binding var selectedDate: [Date]
var body: some View {
Form {
LabeledContent {
TextField("", text: $selectedLabel)
} label: {
Text("Nom")
}
VStack {
ForEach($selectedDate.indices, id: \.self) { i in
HStack {
DatePicker("Quand", selection: $selectedDate[i], displayedComponents: .hourAndMinute)
Button(action: {
selectedDate.remove(at: i)
}) {
Label("", systemImage: "minus.circle.fill")
}.buttonStyle(.borderless)
.disabled(selectedDate.count == 1)
}
}
}
Button(action: {
selectedDate.append(selectedDate.last!)
}) {
Label("Ajouter une notification", systemImage: "plus")
}.buttonStyle(.borderless)
HStack {
Button("Cancel") {
dismiss()
}
if ($selectedReminder.wrappedValue != nil) {
Spacer()
Button("Supprimer") {
deleteReminder()
dismiss()
}.buttonStyle(.bordered)
}
Spacer()
Button("Confirm") {
upsertReminder()
dismiss()
}.buttonStyle(.borderedProminent)
}
}.formStyle(.grouped)
.textFieldStyle(.roundedBorder)
}
private func deleteReminder() {
withAnimation {
cancelNotifications(reminder: $selectedReminder.wrappedValue!)
modelContext.delete($selectedReminder.wrappedValue!)
}
}
private func upsertReminder() {
withAnimation {
let reminder: Reminder
if (selectedReminder != nil) {
cancelNotifications(reminder: $selectedReminder.wrappedValue!)
// Should i Wait ?
selectedReminder!.label = $selectedLabel.wrappedValue
selectedReminder!.when = $selectedDate.wrappedValue
reminder = selectedReminder!
} else {
reminder = Reminder(label: $selectedLabel.wrappedValue, when: $selectedDate.wrappedValue)
modelContext.insert(reminder)
}
scheduleNotifications(reminder: reminder)
}
}
}