add WorkoutStateManager for ViewModel functionality
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
//
|
||||
// WorkoutStateManager.swift
|
||||
// WorkoutsPlus
|
||||
//
|
||||
// Created by Felix Förtsch on 21.11.24.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import SwiftData
|
||||
|
||||
@Observable
|
||||
final class WorkoutStateManager {
|
||||
private let modelContext: ModelContext
|
||||
private(set) var activeWorkoutSession: WorkoutSession?
|
||||
var isWorkoutInProgress: Bool { activeWorkoutSession != nil }
|
||||
|
||||
init(modelContext: ModelContext) {
|
||||
self.modelContext = modelContext
|
||||
}
|
||||
|
||||
func startWorkout(_ workout: Workout) {
|
||||
let session = WorkoutSession(start: workout)
|
||||
modelContext.insert(session)
|
||||
activeWorkoutSession = session
|
||||
}
|
||||
|
||||
func stopWorkout() {
|
||||
if let _ = activeWorkoutSession {
|
||||
activeWorkoutSession = nil
|
||||
}
|
||||
}
|
||||
|
||||
func cancelWorkout(context: ModelContext) {
|
||||
if let session = activeWorkoutSession {
|
||||
context.delete(session)
|
||||
activeWorkoutSession = nil
|
||||
}
|
||||
}
|
||||
|
||||
func prevExercise() {
|
||||
if let session = activeWorkoutSession {
|
||||
session.workoutSessionItems[session.currentExercise].startDate = Date.now
|
||||
if session.currentExercise > 0 {
|
||||
session.currentExercise -= 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nextExercise() {
|
||||
if let session = activeWorkoutSession {
|
||||
session.workoutSessionItems[session.currentExercise].stopDate = Date.now
|
||||
if session.currentExercise < session.workoutSessionItems.count - 1 {
|
||||
session.currentExercise += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getWorkoutDuration() -> String {
|
||||
activeWorkoutSession?.getFormattedDuration() ?? "00:00:00"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user