WatchSessionManager.swift 3.89 KB
//
//  WatchSessionManager.swift
//  hippo-watch Watch App
//
//  Created by shihao on 2025/7/7.
//

import Foundation
import WatchConnectivity
import Combine
import ClockKit

class WatchSessionManager: NSObject, WCSessionDelegate, ObservableObject {
    
    static let share = WatchSessionManager()
    
    override init() {
        super.init()
    }
    
    func addListen() {
        if WCSession.isSupported() {
            WCSession.default.delegate = self
            WCSession.default.activate()
        }
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        print("message-replyHandler: \(message)")
        if let command = message["command"] as? String {
            if command == "watchThemeChanged" {
                NotificationCenter.default.post(name: NotificationType.watchThemeChanged, object: nil)
            }
        }
    }
    
    func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
        DispatchQueue.main.async {
            print("userInfo: \(userInfo)")
            
            if let envValue = userInfo["env"] as? Int,
               let env = NetworkEnvironment(rawValue: envValue) {
                NetworkEnvironment.current = env
            }
            
            if let token = userInfo["token"] as? String {
                WatchUserinfoManager.share.token = token
            }
            
            if let map = userInfo["myUserinfo"] as? [String: Any],
               let data = try? JSONSerialization.data(withJSONObject: map),
               let myUserinfo = try? JSONDecoder().decode(UserInfo.self, from: data) {
                WatchUserinfoManager.share.myUserinfo = myUserinfo
                if let id = myUserinfo.id {
                    ThinkSDKUtil.login(id)
                }
            }
            
            if let map = userInfo["otherUserinfo"] as? [String: Any],
               let data = try? JSONSerialization.data(withJSONObject: map),
               let otherUserinfo = try? JSONDecoder().decode(UserInfo.self, from: data) {
                WatchUserinfoManager.share.otherUserinfo = otherUserinfo
            }
            
            if let interactionActionTypeValue = userInfo["interactionActionType"] as? Int,
               let type = InteractionActionType(rawValue: interactionActionTypeValue) {
                WatchUserinfoManager.share.interactionActionType = type
            }
            
            if let isMeVip = userInfo["isMeVip"] as? Bool {
                WatchUserinfoManager.share.isMeVip = isMeVip
            }
        }
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        print("message: \(message)")
    }

    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        print("applicationContext: \(applicationContext)")
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {
        print("Activation state: \(activationState.rawValue)")
        if let error = error {
            print("Activation error: \(error.localizedDescription)")
        }
    }
    #if os(iOS)
    func sessionDidBecomeInactive(_ session: WCSession) {
        
    }
    func sessionDidDeactivate(_ session: WCSession) {

            WCSession.default.activate()

        }
    #endif
}


extension WatchSessionManager {
    func notifyPhoneToRefreshPulse() {
        if WCSession.default.isReachable {
            WCSession.default.sendMessage(["command": "statusPulseRefresh"],
                                          replyHandler: nil,
                                          errorHandler: { error in
                print("❌ Failed to send refresh message: \(error)")
            })
        } else {
            print("📵 iPhone not reachable")
        }
    }
}