98 lines
3.0 KiB
Swift
98 lines
3.0 KiB
Swift
//
|
|
// WatchMainViewMoel.swift
|
|
// Werkout_watch Watch App
|
|
//
|
|
// Created by Trey Tartt on 6/22/23.
|
|
//
|
|
|
|
import Foundation
|
|
import WatchConnectivity
|
|
import SwiftUI
|
|
import HealthKit
|
|
import os
|
|
import SharedCore
|
|
|
|
class WatchMainViewModel: NSObject, ObservableObject {
|
|
static let shared = WatchMainViewModel()
|
|
let logger = Logger(subsystem: "com.werkout.watch", category: "session")
|
|
|
|
var session: WCSession
|
|
|
|
@Published var watchPackageModel = WatchMainViewModel.defualtPackageModle
|
|
|
|
static var defualtPackageModle: WatchPackageModel {
|
|
WatchPackageModel(currentExerciseName: "", currentExerciseID: -1, currentTimeLeft: -1, workoutStartDate: Date())
|
|
}
|
|
|
|
override init() {
|
|
session = WCSession.default
|
|
super.init()
|
|
|
|
session.delegate = self
|
|
session.activate()
|
|
|
|
}
|
|
|
|
private func send(_ action: WatchActions) {
|
|
do {
|
|
let data = try JSONEncoder().encode(action)
|
|
DataSender.send(data)
|
|
} catch {
|
|
logger.error("Failed to encode watch action: \(error.localizedDescription, privacy: .public)")
|
|
}
|
|
}
|
|
|
|
// actions from view
|
|
func nextExercise() {
|
|
send(.nextExercise)
|
|
WKInterfaceDevice.current().play(.start)
|
|
}
|
|
|
|
func restartExercise() {
|
|
send(.restartExercise)
|
|
WKInterfaceDevice.current().play(.start)
|
|
}
|
|
|
|
func previousExercise() {
|
|
send(.previousExercise)
|
|
WKInterfaceDevice.current().play(.start)
|
|
}
|
|
|
|
func completeWorkout() {
|
|
send(.stopWorkout)
|
|
WKInterfaceDevice.current().play(.start)
|
|
}
|
|
|
|
func pauseWorkout() {
|
|
send(.pauseWorkout)
|
|
WKInterfaceDevice.current().play(.start)
|
|
WatchWorkout.shared.togglePaused()
|
|
}
|
|
|
|
func dataToAction(messageData: Data) {
|
|
do {
|
|
let model = try WatchPayloadValidation.decode(PhoneToWatchActions.self, from: messageData)
|
|
DispatchQueue.main.async {
|
|
switch model {
|
|
case .inExercise(let newWatchPackageModel):
|
|
WatchWorkout.shared.startWorkout()
|
|
if self.watchPackageModel.currentExerciseID != newWatchPackageModel.currentExerciseID {
|
|
WKInterfaceDevice.current().play(.start)
|
|
}
|
|
self.watchPackageModel = newWatchPackageModel
|
|
case .reset:
|
|
self.watchPackageModel = WatchMainViewModel.defualtPackageModle
|
|
WatchWorkout.shared.stopWorkout(sendDetails: false)
|
|
case .endWorkout:
|
|
self.watchPackageModel = WatchMainViewModel.defualtPackageModle
|
|
WatchWorkout.shared.stopWorkout(sendDetails: true)
|
|
case .startWorkout:
|
|
WatchWorkout.shared.startWorkout()
|
|
}
|
|
}
|
|
} catch {
|
|
logger.error("Rejected PhoneToWatchActions payload: \(error.localizedDescription, privacy: .public)")
|
|
}
|
|
}
|
|
}
|