86 lines
3.1 KiB
Swift
86 lines
3.1 KiB
Swift
//
|
|
// FuelLogListView.swift
|
|
// Gas Man
|
|
//
|
|
// Created by Kameron Kenny on 3/17/25.
|
|
//
|
|
|
|
|
|
import SwiftUI
|
|
import CoreData
|
|
|
|
struct FuelLogListView: View {
|
|
@Environment(\.managedObjectContext) private var viewContext
|
|
@FetchRequest(
|
|
sortDescriptors: [NSSortDescriptor(keyPath: \FuelLog.date, ascending: false)],
|
|
animation: .default)
|
|
private var fuelLogs: FetchedResults<FuelLog>
|
|
|
|
@State private var showingAddFuelLog = false // Controls sheet presentation
|
|
|
|
var body: some View {
|
|
NavigationView {
|
|
List {
|
|
ForEach(Array(fuelLogs.enumerated()), id: \.element) { index, log in
|
|
// Compute distance since the previous record:
|
|
let distance: Double? = {
|
|
if index < fuelLogs.count - 1 {
|
|
let previousLog = fuelLogs[index + 1]
|
|
let milesDriven = log.odometer - previousLog.odometer
|
|
return milesDriven > 0 ? milesDriven : nil
|
|
}
|
|
return nil
|
|
}()
|
|
|
|
// Compute MPG (if possible)
|
|
let mpg: Double? = {
|
|
if index < fuelLogs.count - 1 {
|
|
let previousLog = fuelLogs[index + 1]
|
|
let milesDriven = log.odometer - previousLog.odometer
|
|
if log.fuelVolume > 0 && milesDriven > 0 {
|
|
return milesDriven / log.fuelVolume
|
|
}
|
|
}
|
|
return nil
|
|
}()
|
|
|
|
NavigationLink(destination: FuelLogDetailView(fuelLog: log)) {
|
|
FuelLogSummaryView(log: log, mpg: mpg, distanceSincePrevious: distance)
|
|
}
|
|
}
|
|
.onDelete(perform: deleteFuelLogs)
|
|
}
|
|
.listStyle(InsetGroupedListStyle())
|
|
.navigationTitle("Fuel Logs")
|
|
.toolbar {
|
|
ToolbarItem(placement: .navigationBarTrailing) {
|
|
Button(action: {
|
|
showingAddFuelLog = true // Present AddFuelLogView
|
|
}) {
|
|
Label("Add Fuel Log", systemImage: "plus")
|
|
}
|
|
}
|
|
ToolbarItem(placement: .navigationBarLeading) {
|
|
EditButton()
|
|
}
|
|
}
|
|
// Sheet presentation for AddFuelLogView
|
|
.sheet(isPresented: $showingAddFuelLog) {
|
|
AddFuelLogView().environment(\.managedObjectContext, viewContext)
|
|
}
|
|
}
|
|
}
|
|
|
|
private func deleteFuelLogs(offsets: IndexSet) {
|
|
withAnimation {
|
|
offsets.map { fuelLogs[$0] }.forEach(viewContext.delete)
|
|
do {
|
|
try viewContext.save()
|
|
} catch {
|
|
let nsError = error as NSError
|
|
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
|
}
|
|
}
|
|
}
|
|
}
|