//
//  IBTAVAudioPlayWrapper.m
//  Cruiser
//
//  Created by Xummer on 4/17/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "IBTAVAudioPlayWrapper.h"

#import "IBTAudioController.h"

@import AVFoundation;

@interface IBTAVAudioPlayWrapper ()
<
    AVAudioPlayerDelegate
>
{
    AVAudioPlayer* m_audioPlayer;
}

@property (copy, nonatomic) AduioPlayCompleteBlock m_completeBlock;

@end

@implementation IBTAVAudioPlayWrapper
#pragma mark - Life Cycle
- (id)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    return self;
}

- (void)dealloc {
    m_audioPlayer = nil;
}


#pragma mark - Public Method
- (void)playWithPath:(NSString *)path {
    
    // Can not be remote URL
    NSURL *audioUrl = [NSURL fileURLWithPath:path];
    
    [self playWithUrl:audioUrl];
}

- (void)playWithUrl:(NSURL *)audioUrl {
    if (m_audioPlayer) {
        m_audioPlayer.delegate = nil;
        [m_audioPlayer stop];
    }
    
    NSError *error = nil;
    
    m_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioUrl
                                                           error:&error];
    
    if (error) {
        CLog(@"%@", error);
        return;
    }
    
    [self addProximityObersever];
    
    m_audioPlayer.delegate = self;
    m_audioPlayer.volume = 1.0f;
    [m_audioPlayer prepareToPlay];
    
    [m_audioPlayer play];
}

- (void)playWithData:(NSData *)data {
    if (m_audioPlayer) {
        m_audioPlayer.delegate = nil;
        [m_audioPlayer stop];
    }
    
    NSError *error = nil;
    
    m_audioPlayer = [[AVAudioPlayer alloc] initWithData:data
                                                  error:&error];
    
    if (error) {
        CLog(@"%@", error);
        return;
    }
    
    [self addProximityObersever];
    
    m_audioPlayer.delegate = self;
    m_audioPlayer.volume = 1.0f;
    [m_audioPlayer prepareToPlay];
    
    [m_audioPlayer play];
}

- (void)playWithPath:(NSString *)path complete:(AduioPlayCompleteBlock)complete {
    self.m_completeBlock = complete;
    [self playWithPath:path];
}

- (void)playWithUrl:(NSURL *)audioUrl complete:(AduioPlayCompleteBlock)complete {
    self.m_completeBlock = complete;
    [self playWithUrl:audioUrl];
}

- (void)playWithData:(NSData *)data complete:(AduioPlayCompleteBlock)complete {
    self.m_completeBlock = complete;
    [self playWithData:data];
}

- (void)stopPlay {
    if ([m_audioPlayer isPlaying]) {
        [m_audioPlayer stop];
        [[IBTAudioController sharedController] deactivate];
    }
}

#pragma mark - Private Method

#pragma mark -
- (void)addProximityObersever {
    [[IBTAudioController sharedController] switchToPlaybackMode];
    [[IBTAudioController sharedController] activate];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(proximitySensorStateChange:)
                                                 name:UIDeviceProximityStateDidChangeNotification
                                               object:nil];
}

- (void)removeProximityObersever {
    // 关闭距离传感器
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIDeviceProximityStateDidChangeNotification
                                                  object:nil];
    [[IBTAudioController sharedController] switchToPlaybackMode];
}

- (void)proximitySensorStateChange:(NSNotificationCenter *)obj {
    if ([[UIDevice currentDevice] proximityState]) {
        [[IBTAudioController sharedController] switchToPlayAndRecordMode];
    }
    else {
        [[IBTAudioController sharedController] switchToPlaybackMode];
    }
}


#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
    [self removeProximityObersever];
    
    [m_audioPlayer stop];
    m_audioPlayer = nil;
    
    if (_m_completeBlock) {
        _m_completeBlock(YES, nil);
        self.m_completeBlock = nil;
        
        [[IBTAudioController sharedController] deactivate];
    }
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    [self removeProximityObersever];
    
    if (_m_completeBlock) {
        _m_completeBlock(NO, error);
        self.m_completeBlock = nil;
        
        [[IBTAudioController sharedController] deactivate];
    }
}

/* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    
}

/* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
/* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
{
    //    switch (flags) {
    //        case AVAudioSessionInterruptionFlags_ShouldResume:
    //
    //            break;
    //
    //        default:
    //            break;
    //    }
}

@end
