//
//  XXGNetworkMonitor.m
//  XXGPlayKit
//
//  Created by apple on 2025/2/24.
//
#import "XXGNetworkMonitor.h"
@import Network;

static NSString *network_status = nil;
static nw_path_monitor_t currentMonitor = NULL;

@implementation XXGNetworkMonitor

+ (BOOL)xxpk_isConnected {
    return network_status != nil;
}

+ (NSString *)xxpk_networkType {
    return network_status ?: @"none";
}

+ (void)xxpk_checkNetworkTypeAsync:(void (^)(BOOL xxpk_isConnected))completion {
    // 取消之前的监控器
    if (currentMonitor != NULL) {
        nw_path_monitor_cancel(currentMonitor);
        currentMonitor = NULL;
    }
    
    // 创建新的监控器
    currentMonitor = nw_path_monitor_create();
    nw_path_monitor_set_queue(currentMonitor, dispatch_get_main_queue());
    
    __block nw_path_monitor_t blockMonitor = currentMonitor;
    nw_path_monitor_set_update_handler(currentMonitor, ^(nw_path_t path) {
        nw_path_status_t status = nw_path_get_status(path);
        if (status == nw_path_status_satisfied) {
            if (nw_path_uses_interface_type(path, nw_interface_type_wifi)) {
                network_status = @"wifi";
            } else if (nw_path_uses_interface_type(path, nw_interface_type_cellular)) {
                network_status = @"cellular";
            } else {
                // 处理其他接口类型，如以太网、蓝牙等
                network_status = @"other";
            }
            
            // 停止并释放监控器（若只需单次检测）
            if (blockMonitor) {
                nw_path_monitor_cancel(blockMonitor);
                blockMonitor = NULL;
                currentMonitor = NULL;
            }
            
        } else {
            network_status = nil;
        }
        
        // 调用回调
        if (completion) {
            completion([self xxpk_isConnected]);
        }
        
    });
    
    // 开始监控
    nw_path_monitor_start(currentMonitor);
}

@end
