Screaming-Reminder/Screaming Reminder/Views/SheetView.swift
2024-07-30 14:42:42 +02:00

97 lines
2.9 KiB
Swift

//
// 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)
}
}
}