//
//  BridgeModule+Watch.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/19/24.
//

import Foundation
import WatchConnectivity
import AVFoundation
import HealthKit

extension BridgeModule: WCSessionDelegate {
    func sendResetToWatch() {
        let watchModel = PhoneToWatchActions.reset
        let data = try! JSONEncoder().encode(watchModel)
        send(data)
//        self.session.transferUserInfo(["package": data])
    }
    
    func sendStartWorkoutToWatch() {
        let model = PhoneToWatchActions.startWorkout
        let data = try! JSONEncoder().encode(model)
        send(data)
//        self.session.transferUserInfo(["package": data])
    }
    
    func sendWorkoutCompleteToWatch() {
        let model = PhoneToWatchActions.endWorkout
        let data = try! JSONEncoder().encode(model)
        send(data)
//        self.session.transferUserInfo(["package": data])
    }
    
    func sendCurrentExerciseToWatch() {
        if let currentExercise = currentExerciseInfo.currentExercise,
           let duration = currentExercise.duration ,
           duration > 0 {
            let watchModel = WatchPackageModel(currentExerciseName: currentExercise.exercise.name, 
                                               currentExerciseID: currentExercise.id ?? -1,
                                               currentTimeLeft: currentExerciseTimeLeft,
                                               workoutStartDate: workoutStartDate ?? Date())
            let model = PhoneToWatchActions.inExercise(watchModel)
            let data = try! JSONEncoder().encode(model)
            send(data)
        } else {
            if let currentExercise = currentExerciseInfo.currentExercise,
               let reps = currentExercise.reps,
               reps > 0 {
                
                // if not a timer we need to set the watch display with number of reps
                // if timer it will set when timer updates
                let watchModel = WatchPackageModel(currentExerciseName: currentExercise.exercise.name, currentExerciseID: currentExercise.id ?? -1, currentTimeLeft: reps, workoutStartDate: self.workoutStartDate ?? Date())
                let model = PhoneToWatchActions.inExercise(watchModel)
                let data = try! JSONEncoder().encode(model)
                self.send(data)
            }
        }
    }
    
    func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
        if let model = try? JSONDecoder().decode(WatchActions.self, from: messageData) {
            switch model {
            case .nextExercise:
                nextExercise()
                AudioEngine.shared.playFinished()
            case .workoutComplete(let data):
                DispatchQueue.main.async {
                    let model = try! JSONDecoder().decode(WatchFinishWorkoutModel.self, from: data)
                    self.healthKitUUID = model.healthKitUUID
                }
            case .restartExercise:
                restartExercise()
            case .previousExercise:
                previousExercise()
            case .stopWorkout:
                completeWorkout()
            case .pauseWorkout:
                pauseWorkout()
            }
        }
    }
    
    
    func session(_ session: WCSession,
                 activationDidCompleteWith activationState: WCSessionActivationState,
                 error: Error?) {
        switch activationState {
        case .notActivated:
            print("notActivated")
        case .inactive:
            print("inactive")
        case .activated:
            print("activated")
#if os(iOS)
            let workoutConfiguration = HKWorkoutConfiguration()
            workoutConfiguration.activityType = .functionalStrengthTraining
            workoutConfiguration.locationType = .indoor
            if WCSession.isSupported(), session.activationState == .activated, session.isWatchAppInstalled {
                HKHealthStore().startWatchApp(with: workoutConfiguration, completion: { (success, error) in
                    print(error.debugDescription)
                })
            }
#endif
        @unknown default:
            print("default")
        }
    }
#if os(iOS)
    func sessionDidBecomeInactive(_ session: WCSession) {
        
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
        session.activate()
    }
#endif
    func send(_ data: Data) {
        guard session.activationState == .activated else {
            return
        }
#if os(iOS)
        guard session.isWatchAppInstalled else {
            return
        }
#else
        guard session.isCompanionAppInstalled else {
            return
        }
#endif
        session.sendMessageData(data, replyHandler: nil) { error in
            print("Cannot send message: \(String(describing: error))")
        }
    }
}
