//
//  WatchMainViewModel+WCSessionDelegate.swift
//  Werkout_watch Watch App
//
//  Created by Trey Tartt on 6/19/24.
//

import Foundation
import WatchConnectivity
import SwiftUI
import HealthKit

extension WatchMainViewModel: WCSessionDelegate {
    func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
        dataToAction(messageData: messageData)
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        print("activation did complete")
    }
}

class DataSender {
    static func send(_ data: Data) {
        guard WCSession.default.activationState == .activated else {
            return
        }
#if os(iOS)
        guard WCSession.default.isWatchAppInstalled else {
            return
        }
#else
        guard WCSession.default.isCompanionAppInstalled else {
            return
        }
#endif
        WCSession.default.sendMessageData(data, replyHandler: nil)
        { error in
            print("Cannot send message: \(String(describing: error))")
        }
    }
}

extension WatchMainViewModel {
    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
        if let messageData = applicationContext["package"] as? Data {
            dataToAction(messageData: messageData)
        }
        
    }
    
    public func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
        if let messageData = userInfo["package"] as? Data {
            dataToAction(messageData: messageData)
        }
    }
}
