//
//  MKRBTRadioControlManager.m
//  MaoKRadioPlayer
//
//  Created by yyqxiaoyin on 2019/4/7.
//  Copyright © 2019 Muzen. All rights reserved.
//

#import "MKRBTRadioControlManager.h"
#import "MKRAVPlayer.h"

@interface MKRBTRadioControlManager ()<MKRAVPlayerDelegate>

@property (nonatomic, strong) MKRAVPlayer *player;

@property (nonatomic, strong) NSArray <id<MKRRadioResorce>>*playList;

@end

@implementation MKRBTRadioControlManager

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

#pragma mark - private method

- (void)playSongs:(NSArray <id<MKRRadioResorce>> *)songs{
    [self playSongs:songs atIndex:0];
}

- (void)playSongs:(NSArray <id<MKRRadioResorce>> *)songs atIndex:(NSInteger)index{
    if (self.player) {
        [self.player resetPlayer];
    }
    self.playList = songs;
    NSArray *urls = [self.playList valueForKey:@"songUrl"];
    self.player = [[MKRAVPlayer alloc] initWithPlayList:urls];
    self.player.shouldAutoPlay = YES;
    self.player.delegate = self;
    [self.player playAtIndex:index];
}

#pragma mark - MKRAVPlayerDelegate
- (void)songPlayUrlWithIndex:(NSInteger)index completion:(MKRAVPlayerURLRequsetBlcok)completion{
    id song = [self.playList objectAtIndex:index];
//    [MKRRadioResourceTool realUrlBySong:song completion:^(NSString *songRealurl, NSError *error) {
//        if (error) {
//            return ;
//        }
//        completion(songRealurl);
//    }];
    completion(@"");
}

#pragma mark - MKRPlayControlProtocol
- (id <MKRRadioResorce>)currentPlayingSong {
    if (self.player.currentIndex >= _playList.count) return nil;
    return  _playList[self.player.currentIndex];
}

- (void)play{
    [self.player play];
}

- (void)pause{
    [self.player pause];
}

- (void)stop{
    [self.player pause];
    [self.player resetPlayer];
}

- (void)next{
    [self.player next];
}

- (void)previous{
    [self.player previous];
}

- (void)seekToTimeInterval:(NSTimeInterval)timeInterval{
    self.player.currentTime = timeInterval;
}

- (void)playSongWithChannelNO:(NSString *)channelNO userID:(NSString *)userID {
    [self playSongWithChannelNO:channelNO index:0 userID:nil];
}

- (void)playSongWithChannelNO:(NSString *)channelNO index:(NSInteger)index userID:(NSString *)userID {
//    NSArray *songs = [MKROneSong songsByChannelNO:[channelNO integerValue]];
//    [self playSongs:songs atIndex:index];
}

- (void)playTempSongs:(NSArray <id <MKRRadioResorce>> *)songs userID:(NSString *)userID {
    [self playTempSongs:songs index:0 userID:nil];
}

- (void)playTempSongs:(NSArray <id <MKRRadioResorce>> *)songs index:(NSInteger)index userID:(NSString *)userID {
    [self playSongs:songs atIndex:index];
}

@end
