//
//  MKRWIFIDeviceManager.m
//  MKRAVPlayer
//
//  Created by yyqxiaoyin on 2019/4/16.
//

#import "MKRWIFIDeviceManager.h"
#import "NSString+MKRRadioManagerAdd.h"
#import "UIDevice+MKRRadioManagerAdd.h"
#import <pthread.h>
#import <libAS-Control/ASControlTools.h>
#import <libAS-Control/NSDictionary+MKRXml.h>
#import <NSHashTable+MKRRadioManagerAdd.h>

static inline void wd_main_queue(void (^block)(void)){
    if (pthread_main_np()) {
        block();
    }else{
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

static inline void wd_playControl_queue(void (^block)(void)){
    dispatch_queue_t queue = dispatch_queue_create("com.maoking.playControlQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, block);
}

@interface MKRWIFIDeviceManager () <ASControlDelegate> {
    int _upnpErrorCode;
    NSMutableArray *_baseUrlArray;
    dispatch_source_t _searchTimer;
    NSString *_ssid;
    BOOL _shutDownUpnping;
    BOOL _updateLocalResourceLock;
}

@property (nonatomic, strong) NSHashTable *listeners;

@property (nonatomic, strong) id <MKRRadioResorce> currentResource;

@end

@implementation MKRWIFIDeviceManager

- (instancetype)init {
    if (self = [super init]) {
        _upnpErrorCode = -1;
        [self startUpnp];
        [ASControlTools sharedInstanceUPNP].delegate = self;
    }
    return self;
}

+ (instancetype)shareManager {
    static MKRWIFIDeviceManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MKRWIFIDeviceManager alloc] init];
    });
    return manager;
}

- (void)addDeviceManagerListener:(id<MKRWIFIDeviceManagerDelegate>)listener{
    if (![self.listeners containsObject:listener]){
        [self.listeners addObject:listener];
    }
}

- (void)removeDeviceManagerListener:(id<MKRWIFIDeviceManagerDelegate>)listener{
    if ([self.listeners containsObject:listener]) {
        [self.listeners removeObject:listener];
    }
}

- (NSInteger)startUpnp {
    NSString *userPhoneName = [[UIDevice currentDevice] name];
    NSString *sharePath = NSHomeDirectory();
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentSharePath = [paths objectAtIndex:0];
    NSString *sharePath2 = NSTemporaryDirectory();
    NSArray *dirArgv =[[NSArray alloc] initWithObjects:DocumentSharePath,sharePath2,nil];
    libupnp_RELoadUpnp();
    _upnpErrorCode = libupnp_UpnpStartTest([UIDevice currentDeviceMacAddress],userPhoneName,2,dirArgv,[UIDevice currentDeviceInfo],7);
    if (_upnpErrorCode == 0) {
        NSLog(@"upnp初始化成功");
        _upnpErrorCode = libupnp_UpnpSetWebServerRootDir(sharePath);
    }else if(_upnpErrorCode == -100) {
        NSLog(@"UpnpStart 无网络连接!! ==> %d ", _upnpErrorCode);
    }else{//UPNP_ERROR
        NSLog(@"UpnpStart Error!! ==>  %d" ,_upnpErrorCode);
    }
    return _upnpErrorCode;
}

- (void)stopUpnp{
    wd_playControl_queue(^{
        libupnp_StopBuildFilesList();
        [NSThread sleepForTimeInterval:5];
        if(_upnpErrorCode == 0){
            libupnp_UpnpQuickExit();
        }
    });
}

- (void)reloadUpnp{
    NSString *ssid = [UIDevice currentSSID];
    if ([ssid isEqualToString:_ssid]) {
        return;
    }
    if (_shutDownUpnping) {
        return;
    }
    _ssid = ssid;
    wd_playControl_queue(^{
        _shutDownUpnping = YES;
        libupnp_StopBuildFilesList();
        int exitCount = 0;
        while (_updateLocalResourceLock) {
            exitCount++;
            [NSThread sleepForTimeInterval:1.0];
            if (exitCount > 10)
                break;
        }
        _updateLocalResourceLock = NO;
        [self searchDeviceWithSearchTime:20 timeBlock:nil];
    });
}

- (void)searchDeviceWithSearchTime:(int)searchTime
                         timeBlock:(void(^)(NSInteger time))timeBlock {
    wd_playControl_queue(^{
        _updateLocalResourceLock = YES;
        if (_upnpErrorCode != 0) {
            if ([self startUpnp] == 0) {
                [self checkBaseURL];
                libupnp_BuildFilesList();
            }
        }
        libupnp_SearchDevice(20);
    });
    _ssid = [UIDevice currentSSID];
    __block int count = searchTime +1;
    _searchTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(_searchTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_searchTimer, ^{
        if (timeBlock) {
            wd_main_queue(^{
                timeBlock(count);
            });
        }
        count --;
        if (count == 0) {
            dispatch_source_cancel(self->_searchTimer);
        }
    });
    dispatch_source_set_cancel_handler(_searchTimer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"搜索结束");
        });
    });
    dispatch_resume(_searchTimer);
}

- (void)checkBaseURL{
    NSMutableArray *baseURLArray = [NSMutableArray array];
    for (NSString *baseValue in _baseUrlArray) {
        NSString *tempStr = [baseValue stringByReplacingOccurrencesOfString:@"49152" withString:@"MaoKing"];
        tempStr = [tempStr stringByReplacingOccurrencesOfString:@"49153" withString:@"MaoKing"];
        tempStr = [tempStr stringByReplacingOccurrencesOfString:@"49154" withString:@"MaoKing"];
        [baseURLArray addObject:[tempStr stringByReplacingOccurrencesOfString:@"MaoKing" withString:@"49152"]];
        [baseURLArray addObject:[tempStr stringByReplacingOccurrencesOfString:@"MaoKing" withString:@"49153"]];
        [baseURLArray addObject:[tempStr stringByReplacingOccurrencesOfString:@"MaoKing" withString:@"49154"]];
    }
    if([baseURLArray count] > 0)libupnp_FirstCheckByBaseURL((int)[baseURLArray count] , baseURLArray);
}

#pragma mark - ASControlDelegate

-(void)ReceivedPlayCallBack:(NSString *)nUDN{
    NSLog(@"收到播放回调%@",nUDN);
    wd_main_queue(^{
        if ([nUDN isEqualToString:self.device.deviceUUID]) {
            self.currentResource.resourceStatus.playState = MKRResourcePlayStatePlaying;
            [self.listeners makeObjectsPerformSelectorWithObjects:@selector(didReceivePlayStateChange:),MKRResourcePlayStatePlaying];
        }
    });
}

-(void)ReceivedPauseCallBack:(NSString *)nUDN{
    NSLog(@"收到暂停回调%@",nUDN);
    wd_main_queue(^{
        if ([nUDN isEqualToString:self.device.deviceUUID]) {
            self.currentResource.resourceStatus.playState = MKRResourcePlayStatePause;
            [self.listeners makeObjectsPerformSelectorWithObjects:@selector(didReceivePlayStateChange:),MKRResourcePlayStatePause];
        }
    });
}

-(void)ReceivedStopCallBack:(NSString *)nUDN{
    NSLog(@"收到停止回调%@",nUDN);
    wd_main_queue(^{
        if ([nUDN isEqualToString:self.device.deviceUUID]) {
            self.currentResource.resourceStatus.playState = MKRResourcePlayStateStopped;
            [self.listeners makeObjectsPerformSelectorWithObjects:@selector(didReceivePlayStateChange:),MKRResourcePlayStateStopped];
        }
    });
}

-(void)ReceivedSetVolumeCallBack:(NSString *)nUDN Volume:(NSInteger)Volume{
     wd_main_queue(^{
               if ([nUDN isEqualToString:self.device.deviceUUID]) {
                   NSLog(@"收到设备音量回调SetZoneVolumeCallBack：%zd",Volume);
                   [self.listeners makeObjectsPerformSelectorWithObjects:@selector(didReceiveVolumeChange:),(float)Volume];
               }
           });
}

-(void)ReceivedSetMuteCallBack:(NSString *)nUDN Mute:(NSInteger)Mute{
    NSLog(@"%s",__func__);
}

-(void)ReceivedSetZoneMuteCallBack:(NSString *)nUDN Mute:(NSInteger)Mute{
    NSLog(@"%s",__func__);
}

-(void)ReceivedSetGroupIdCallBack:(NSString *)nUDN GrouId:(NSString *)GroupId{
    NSLog(@"%s",__func__);
}

-(void)ReceivedSetSleepStateCallBack:(NSString *)nUDN SleepState:(NSString *)SleepState{
    NSLog(@"%s",__func__);
}

-(void)ReceivedSetSoundSourceCallBack:(NSString *)nUDN SoundSource:(NSString *)SoundSource{
    NSLog(@"%s",__func__);
}

-(void)ReceivedSetVolumeChannelCallBack:(NSString *)nUDN Channel:(NSString *)Channel {
    NSLog(@"ReceivedSetVolumeChannelCallBack-------------%@ ",Channel);
}

-(void)ReceivedSetZoneVolumeCallBack:(NSString *)nUDN Volume:(NSInteger)Volume {
    NSLog(@"%s",__func__);
}

-(void)CallBackRemoveZoneMedia:(NSString *)nByeUDN BaseURL:(NSString *)BaseURL{
    NSLog(@"%s",__func__);
    
}

-(void)CallBackRemoveRenderer:(NSString *)nByeUDN BaseURL:(NSString *)BaseURL
{
    NSLog(@"CallBackRemoveRenderer---------%@",nByeUDN);
    NSLog(@"%s",__func__);
}

-(void)CallBackRemoveDMS:(NSString *)nByeUDN BaseURL:(NSString *)BaseURL{
    NSLog(@"%s",__func__);
}

-(void)CallBackAddZoneMedia:(NSArray *)nStr Size:(NSInteger)size{
    NSLog(@"搜索到设备：%@",nStr);
    NSLog(@"%s",__func__);
    wd_playControl_queue(^{
        [self addDevice:nStr];
    });
}

- (void)updateClockID:(NSString *)clockID clockDic:(NSDictionary *)clockDic clockTime:(NSString *)clockTime operationType:(BOOL)isOn deleteClock:(BOOL)isDelete{
    NSLog(@"%s",__func__);
}

-(void)CallBackAddMediaServer:(NSArray *)nStr Size:(NSInteger)size{
    NSLog(@"%s",__func__);
}


-(void)CallBackAddMediaRenderer:(NSArray *)nStr Size:(NSInteger)size{
    NSLog(@"%s",__func__);
}


-(void)ReceivedChangeChannelCallBack:(NSString *)nUDN Channel:(NSString *)channel{
    NSLog(@"%s",__func__);
    NSLog(@"收到频道改变回调%@",nUDN);
    wd_main_queue(^{
        if ([nUDN isEqualToString:self.device.deviceUUID]) {
            [self.listeners makeObjectsPerformSelectorWithObjects:@selector(didReceivePlayingChannelChange:),[channel integerValue]];
        }
    });
}

-(void)getLocalIp:(NSString *)Ip{
    NSLog(@"%s",__func__);
}

-(void)AddLocalResource:(NSArray *)oneSongID3Info{
    NSLog(@"%s",__func__);
}

-(void)UpdateLocalResourceFinish{
    NSLog(@"%s",__func__);
}

- (void)addDevice:(NSArray *)array {
    NSMutableDictionary *deviceDict = [NSMutableDictionary dictionary];
    [deviceDict setObject:array[0] forKey:@"deviceName"];
    [deviceDict setObject:array[1] forKey:@"deviceUUID"];
    [deviceDict setObject:array[2] forKey:@"deviceBaseUrl"];
    [deviceDict setObject:array[5] forKey:@"connectionManagerUrl"];
    [deviceDict setObject:array[7] forKey:@"avTransportUrl"];
    [deviceDict setObject:array[9] forKey:@"renderingControlUrl"];
    [deviceDict setObject:array[11] forKey:@"groupManagementUrl"];
    NSArray *deviceInfo = [[ASControlTools sharedInstanceUPNP] libupnp_GetDeviceInfo:array[11] ServiceTYPE:array[10]];
    if(deviceInfo == nil || [deviceInfo isEqual:[NSNull null]]){
        return;
    }
    [deviceDict setObject:deviceInfo[0] forKey:@"devGId"];
    [deviceDict setObject:deviceInfo[1] forKey:@"devWiFiDB"];
    [deviceDict setObject:[deviceInfo[16] length]?deviceInfo[16]: @"AWAKE" forKey:@"devSleepStatus"];
    [deviceDict setObject:[deviceInfo[17] length]?deviceInfo[17]: @"WIFI" forKey:@"devSource"];
    [deviceDict setObject:[deviceInfo[28] length]?deviceInfo[28]:@"WIFI" forKey:@"devSourceList"];
    [deviceDict setObject:deviceInfo[12] forKey:@"channelLR"];
    [deviceDict setObject:[deviceInfo[29] length] ? deviceInfo[29]: @"0.0.0.0" forKey:@"devType"];
    [deviceDict setObject:[deviceInfo[32] length] ? deviceInfo[32]: @"" forKey:@"deviceClockInfo"];
    [deviceDict setObject:[deviceInfo[33] length]? deviceInfo[33]:@"NULL" forKey:@"devPower"];
    [deviceDict setObject:[deviceInfo[36] length] ? deviceInfo[36]:@"NULL" forKey:@"devUserID"];
    NSString *devFlag = [NSString stringWithFormat:@"%@-%@",deviceInfo[9],deviceInfo[10]];
    [deviceDict setObject:devFlag forKey:@"devFlag"];
    [deviceDict setObject:[deviceInfo[18] length] ?deviceInfo[18]:@"MJ_M" forKey:@"devProductModel"];
    [deviceDict setObject:[deviceInfo[39] length] ?deviceInfo[39] :@"0" forKey:@"devOpenLowPowerNotice"];
    [deviceDict setObject:[deviceInfo[19] length] ? deviceInfo[19] : @"1.0.0" forKey:@"devVersion"];
    [deviceDict setObject:[deviceInfo[41] length] ? deviceInfo[41] :@"" forKey:@"devDuerAccessToken"];
    [deviceDict setObject:[deviceInfo[42] length] ?deviceInfo[42] : @"" forKey:@"devDuerRefreshToken"];
    [deviceDict setObject:deviceInfo[13] forKey:@"volume"];
    [deviceDict setObject:deviceInfo[14] forKey:@"mute"];
    [deviceDict setObject:[deviceInfo[40] length] ?deviceInfo[40] :@"-1" forKey:@"devPauseShutDownTime"];
    NSString *devNowStatus = [deviceInfo[2] length] ? deviceInfo[2] : @"STOPPED";
    [deviceDict setObject:devNowStatus forKey:@"devNowStatus"];
    [deviceDict setObject:@"REPEAT_ALL" forKey:@"devNowPlayMode"];
    NSURL *url = [NSURL URLWithString:array[2]];
    [deviceDict setObject:url.URLByDeletingLastPathComponent.absoluteString?:@"" forKey:@"devIP"];
    if([devNowStatus isEqualToString:@"PAUSED_PLAYBACK"]){
        NSString *devNowPlaying = [NSString stringWithFormat:@"Pause:%@",deviceInfo[3]];
        [deviceDict setObject:devNowPlaying forKey:@"devNowPlaying"];
    }else if([devNowStatus isEqualToString:@"PLAYING"]){
        [deviceDict setObject:deviceInfo[3] forKey:@"devNowPlaying"];
    }
    [deviceDict setObject:deviceInfo[4] forKey:@"devNowArtist"];
    if([deviceDict[@"devNowPlaying"] isEqualToString:@"Unknown:TrackMetaData Incomplete"]){
        [deviceDict setObject:@"No Music" forKey:@"devNowPlaying"];
    }
    if([deviceDict[@"devNowArtist"] isEqualToString:@"Unknown:TrackMetaData Incomplete"])
    {
        [deviceDict setObject:@"Unknown" forKey:@"devNowArtist"];
    }
    if(deviceDict[@"devNowArtist"] == nil||[deviceDict[@"devNowArtist"] isEqual:[NSNull null]]){
        [deviceDict setObject:@"Unknown" forKey:@"devNowArtist"];
    }
    [deviceDict setObject:@"1" forKey:@"isOnLine"];
    wd_main_queue(^{
        id<MKRWIFIDeviceManagerDelegate> obj;
        NSEnumerator *enumerator = [self.listeners objectEnumerator];
        while ((obj = [enumerator nextObject]) != nil) {
            if ([obj respondsToSelector:@selector(didSearchNewDevice:)]) {
                [obj didSearchNewDevice:deviceDict];
            }
        }
    });
}

- (void)setM3UList:(MKRM3UListModel *)m3uListModel{
    libupnp_SetNewM3UListV2(m3uListModel.secondsList,
    m3uListModel.artistList,
    m3uListModel.titleList,
    m3uListModel.urlList,
    m3uListModel.songFromList,
    m3uListModel.channelNO,
    m3uListModel.playModeString,
    m3uListModel.timeString,
    m3uListModel.startIndex,
    m3uListModel.endIndex,
    m3uListModel.m3uSize,
    m3uListModel.channelID,
    m3uListModel.channelInfoString);
}

- (void)setAVTransportURIWithSong:(id <MKRRadioResorce>)song
                           device:(id <MKRUPnPDevice>)device{
    NSString *timestamp = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    NSString *channelNumString = @(song.songChannel).stringValue;
    NSString *userID = self.userID;
    NSString *songUrlString = [NSString stringWithFormat:@"AIRSMART//ID_%zd//",song.songID];
    NSString *songFrom = [NSString stringWithFormat:@"1//%zd//%zd//",[MKRM3UListModel convertAudioTypeWithSorceType:song.sourceType],song.songID];
    libupnp_SetAVTransportURIV2(
    device.avTransportUrl,
    songUrlString,
    song.songName?:@"",
    song.songArtist?:@"",
    song.songAlbum?:@"",
    song.songAlbumCover?:@"",
    @"0",
    @"null",
    @"null",
    timestamp,
    channelNumString,
    @"0",
    userID?:@"",
    @(song.songID).stringValue,
    songFrom,
    song.songAlbumID?:@""
    );
    
}

- (void)playWithDevice:(id <MKRUPnPDevice>)device {
    libupnp_PlayV2(device.avTransportUrl);
}

- (void)_playPlayFlag:(NSString *)playFlag
              device:(id <MKRUPnPDevice>)device
           timeStamp:(NSTimeInterval)timeStamp{
    NSString *playListUrl = [NSString stringWithFormat:@"%@/web/playlist",[ASControlTools sharedInstanceUPNP].myIp];
    NSString *timestamp = [NSString stringWithFormat:@"%.0f", timeStamp];
    NSString *userID = self.userID;
    libupnp_PlayNumFlag(
    device.avTransportUrl,
    playFlag,
    timestamp,
    userID,
    playListUrl,
    @"0"
    );
}

- (void)playSongWithChannelNO:(NSInteger)channelNO
             firstPlayingSong:(id<MKRRadioResorce>)firstPlayingSong
                       device:(id<MKRUPnPDevice>)device
                    timeStamp:(NSTimeInterval)timeStamp{
    wd_playControl_queue(^{
        if (firstPlayingSong && firstPlayingSong.songID) {
            [self setAVTransportURIWithSong:firstPlayingSong device:device];
        }
        NSString *playFlag = [NSString stringWithFormat:@"%zd",channelNO];
        [self _playPlayFlag:playFlag device:device timeStamp:timeStamp];
    });
}

- (void)playSongWithChannelNO:(NSInteger)channelNO
             firstPlayingSong:(id<MKRRadioResorce>)firstPlayingSong
                        index:(NSInteger)index
                       device:(id<MKRUPnPDevice>)device
                    timeStamp:(NSTimeInterval)timeStamp{
    wd_playControl_queue(^{
        if (firstPlayingSong && firstPlayingSong.songID) {
            [self setAVTransportURIWithSong:firstPlayingSong device:device];
        }
        NSString *playFlag = [NSString stringWithFormat:@"%zd-%zd",channelNO,index];
        [self _playPlayFlag:playFlag device:device timeStamp:timeStamp];
    });
}

- (void)playTempChannelSongs:(NSArray<id<MKRRadioResorce>> *)songs
                       index:(NSInteger)index
                      device:(id<MKRUPnPDevice>)device
                   timeStamp:(NSTimeInterval)timeStamp{
    MKRM3UListModel *m3uModel = [MKRM3UListModel tempChannelM3UModelWithSongs:songs startIndex:index];
    m3uModel.userID = self.userID;
    m3uModel.playModeString = @"REPEAT_ALL";
    wd_playControl_queue(^{
        [[MKRWIFIDeviceManager shareManager] setM3UList:m3uModel];
        id <MKRRadioResorce> song = songs[index];
        song.songChannel = 13;
        [self setAVTransportURIWithSong:song device:device];
        NSString *playFlag = [NSString stringWithFormat:@"13-%zd",index];
        [self _playPlayFlag:playFlag device:device timeStamp:timeStamp];
    });
}

- (void)playTempChannelSongs:(NSArray<id<MKRRadioResorce>> *)songs
                      device:(id<MKRUPnPDevice>)device
                   timeStamp:(NSTimeInterval)timeStamp{
    MKRM3UListModel *m3uModel = [MKRM3UListModel tempChannelM3UModelWithSongs:songs startIndex:index];
    m3uModel.userID = self.userID;
    m3uModel.playModeString = @"REPEAT_ALL";
    wd_playControl_queue(^{
        [[MKRWIFIDeviceManager shareManager] setM3UList:m3uModel];
        id <MKRRadioResorce> song = songs[0];
        song.songChannel = 13;
        [self setAVTransportURIWithSong:song device:device];
        [self _playPlayFlag:@"13" device:device timeStamp:timeStamp];
    });
}

- (void)pauseWithDevice:(id <MKRUPnPDevice>)device {
    wd_playControl_queue(^{
        libupnp_Pause(device.avTransportUrl);
    });
}

- (void)nextWithDevice:(id <MKRUPnPDevice>)device{
    wd_playControl_queue(^{
        libupnp_Next(device.avTransportUrl);
    });
}

- (void)previousWithDevice:(id <MKRUPnPDevice>)device{
    wd_playControl_queue(^{
        libupnp_Previous(device.avTransportUrl);
    });
    
}

- (void)stopWithDevice:(id <MKRUPnPDevice>)device{
    wd_playControl_queue(^{
        libupnp_Stop(device.avTransportUrl);
    });
}

- (void)setVolume:(int)volume device:(id <MKRUPnPDevice>)device{
    wd_playControl_queue(^{
        libupnp_SetZoneVolume(
        device.groupManagementUrl,
        @"urn:schemas-upnp-org:service:GroupManagement:1",
        @"Master",
        volume
        );
    });
    
}

- (void)seekToTimeInterval:(NSInteger)timeInterval device:(id <MKRUPnPDevice>)device {
    NSString *timeString = [NSString HHmmssFormatStrig:timeInterval];
    wd_playControl_queue(^{
        libupnp_SetMediaSeek(device.avTransportUrl, timeString);
    });
}

- (void)clearChannelWithChannelNO:(NSString *)channelNO device:(id <MKRUPnPDevice>)device {
    NSString *channelID = [NSString stringWithFormat:@"CHANNEL_UPDATE_%@",channelNO];
    NSString *timestamp = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    wd_playControl_queue(^{
        libupnp_SetChannelClear(device.groupManagementUrl, channelID, timestamp);
    });
}

- (void)setChannelUpdate:(NSString *)channelFlag device:(id<MKRUPnPDevice>)device timeStamp:(NSTimeInterval)timeStamp{
    NSString *timestamp = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    libupnp_SetChannelUpdateV2(device.groupManagementUrl, self.userID, timestamp, channelFlag, @"null");
}

- (id <MKRRadioResorce>)getPlayingStatusWithDevice:(id <MKRUPnPDevice>)device {
    wd_playControl_queue(^{
        NSDictionary *resultDic = [[ASControlTools sharedInstanceUPNP] libupnp_getPlayInfo:device.avTransportUrl];
        if (!resultDic || !resultDic.allKeys.count) {
            return ;
        }
        @synchronized (self.currentResource) {
            if ([resultDic[@"TrackMetaData"][@"upnp:songName"] isKindOfClass:NSString.class]) {
                self.currentResource.songName = resultDic[@"TrackMetaData"][@"upnp:songName"];
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songPlayer"] isKindOfClass:NSString.class]) {
                self.currentResource.songArtist = resultDic[@"TrackMetaData"][@"upnp:songPlayer"];
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songThumb"] isKindOfClass:NSString.class]) {
                self.currentResource.songAlbumCover = resultDic[@"TrackMetaData"][@"upnp:songThumb"];
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songInfoID"] isKindOfClass:NSString.class]) {
                self.currentResource.songID = [resultDic[@"TrackMetaData"][@"upnp:songInfoID"] integerValue];
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songPlatform"] isKindOfClass:NSString.class]) {
                self.currentResource.songFrom = [resultDic[@"TrackMetaData"][@"upnp:songPlatform"] integerValue];
            }
            if ([resultDic[@"TrackDuration"] isKindOfClass:NSString.class]) {
                self.currentResource.resourceStatus.totalTime = [NSString secondsFromHHmmssFormatStrig:resultDic[@"TrackDuration"]];
            }
            if ([resultDic[@"RelTime"] isKindOfClass:NSString.class]) {
                self.currentResource.resourceStatus.currentTime = [NSString secondsFromHHmmssFormatStrig:resultDic[@"RelTime"]];
            }
            if ([resultDic[@"CurrentTransportState"] isKindOfClass:NSString.class]) {
                self.currentResource.resourceStatus.playState = [self.currentResource.resourceStatus updatePlayState:resultDic[@"CurrentTransportState"]];
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songType"] isKindOfClass:NSString.class]) {
                NSInteger sourceType = [MKRM3UListModel convertSorceTypeWithAudioType:[resultDic[@"TrackMetaData"][@"upnp:songType"] integerValue]];
                self.currentResource.sourceType = sourceType;
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songAlbumID"] isKindOfClass:NSString.class]) {
                id songAlbumID = resultDic[@"TrackMetaData"][@"upnp:songAlbumID"];
                if ([songAlbumID isKindOfClass:NSString.class]) {
                    self.currentResource.songAlbumID = resultDic[@"TrackMetaData"][@"upnp:songAlbumID"];
                }
            }
            if ([resultDic[@"TrackMetaData"][@"upnp:songAlbumID"] isKindOfClass:NSString.class]) {
                id songAlbumID = resultDic[@"TrackMetaData"][@"upnp:songAlbumID"];
                if ([songAlbumID isKindOfClass:NSString.class]) {
                    self.currentResource.songAlbumID = resultDic[@"TrackMetaData"][@"upnp:songAlbumID"];
                }
            }
            NSString *channelString = resultDic[@"TrackMetaData"][@"upnp:songFlag"];
            NSInteger songChannel = 0;
            if ([channelString containsString:@"-"]) {
                NSArray *channelStringArr = [channelString componentsSeparatedByString:@"-"];
                songChannel = [[channelStringArr firstObject] integerValue];
            }else{
                songChannel = [channelString integerValue];
            }
            self.currentResource.songChannel = songChannel;
            NSString *songChannelUid = [NSString stringWithFormat:@"%@-%@-%zd",self.userID,device.deviceUUID,songChannel];
            self.currentResource.songChannelUid = songChannelUid;
            self.currentResource.songFlag = [NSString stringWithFormat:@"%@_%zd_%zd",songChannelUid,self.currentResource.songID,self.currentResource.songFrom];
        }
    });
    return self.currentResource;
}

- (void)mkr_setObject:(id)obj forKey:(NSString *)key{
    
}

- (id<MKRRadioResorce>)currentResource{
    if (!_currentResource) {
        _currentResource = [[MKRRadioResorce alloc] init];
        _currentResource.songName = @"猫王妙播";
        _currentResource.songArtist = @"Keep radio on！";
        if (!_currentResource.resourceStatus) {
            _currentResource.resourceStatus = [[MKRPlayResourceStatus alloc] init];
        }
    }
    return _currentResource;
}

- (NSHashTable *)listeners{
    if (!_listeners) {
        _listeners = [NSHashTable weakObjectsHashTable];
    }
    return _listeners;
}

@end
