//
//  RCTRemoteControl.m
//  RCTOMPlayer
//
//  Created by chenguanglv on 2017/9/20.
//  Copyright © 2017年 Anren. All rights reserved.
//

#import "RCTRemoteControl.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "RCTRemoteControlName.h"
#import "RCTRemoteControlEvent.h"

@interface RCTRemoteControl()

@property (nonatomic, strong) NSMutableDictionary *nowPlaying;
@property (nonatomic, strong) NSString *artworkUrl;

@end

@implementation RCTRemoteControl

@synthesize bridge = _bridge;
@synthesize methodQueue = _methodQueue;

RCT_EXPORT_MODULE(RemoteControlManager);

- (NSArray<NSString *> *)supportedEvents
{
    return @[
             EVENT_REMOTE_CONTROL_PLAY,
             EVENT_REMOTE_CONTROL_PAUSE,
             EVENT_REMOTE_CONTROL_PREV,
             EVENT_REMOTE_CONTROL_NEXT,
             REMOTE_CONTROL_NEXT,
             REMOTE_CONTROL_PREV,
             REMOTE_CONTROL_PAUSE,
             REMOTE_CONTROL_PLAY
             ];
}

- (NSDictionary *)constantsToExport
{
    return @{ EVENT_REMOTE_CONTROL_NEXT: EVENT_REMOTE_CONTROL_NEXT,
              EVENT_REMOTE_CONTROL_PREV: EVENT_REMOTE_CONTROL_PREV,
              EVENT_REMOTE_CONTROL_PLAY: EVENT_REMOTE_CONTROL_PLAY,
              EVENT_REMOTE_CONTROL_PAUSE: EVENT_REMOTE_CONTROL_PAUSE,
              REMOTE_CONTROL_NEXT: REMOTE_CONTROL_NEXT,
              REMOTE_CONTROL_PREV: REMOTE_CONTROL_PREV,
              REMOTE_CONTROL_PAUSE: REMOTE_CONTROL_PAUSE,
              REMOTE_CONTROL_PLAY: REMOTE_CONTROL_PLAY,
              @"MediaPropTitle": MPMediaItemPropertyTitle,
              @"MediaPropArtist": MPMediaItemPropertyArtist,
              @"MediaPropAlbum": MPMediaItemPropertyAlbumTitle,
              @"MediaPropArtwork": MPMediaItemPropertyArtwork,
              @"MediaPropDuration": MPMediaItemPropertyPlaybackDuration,
              @"MediaPropElapsed": MPNowPlayingInfoPropertyElapsedPlaybackTime
              };
}


RCT_EXPORT_METHOD(setNowPlayingInfo:(NSDictionary*)info)
{
    self.nowPlaying = [[NSMutableDictionary alloc] initWithDictionary:info];
    NSString *artworkUrl = info[MPMediaItemPropertyArtwork];
    self.artworkUrl = artworkUrl;
    
    if(artworkUrl)
    {
        [self.nowPlaying removeObjectForKey:MPMediaItemPropertyArtwork];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            UIImage *image = nil;
            
            if (!artworkUrl ||artworkUrl.length > 0)
            {
                if ([artworkUrl hasPrefix: @"http://"] || [artworkUrl hasPrefix:@"https://"])
                {
                    NSURL *imageURL = [NSURL URLWithString:artworkUrl];
                    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
                    image = [UIImage imageWithData:imageData];
                }
                else
                {
                    if ([[NSFileManager defaultManager] fileExistsAtPath:artworkUrl])
                    {
                        image = [UIImage imageNamed:artworkUrl];
                    }
                }
            }
            
            if (image)
            {
                CGImageRef cgref = [image CGImage];
                CIImage *cim = [image CIImage];
                
                if ( cgref || cim )
                {
                    dispatch_async(self.methodQueue, ^{
                        if ([artworkUrl isEqualToString:self.artworkUrl]) {
                            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
                            [self.nowPlaying setObject:artwork forKey:MPMediaItemPropertyArtwork];
                            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:self.nowPlaying];
                        }
                    });
                }
            }
        });
    }
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:self.nowPlaying];
}

RCT_EXPORT_METHOD(resetNowPlayingInfo)
{
    self.nowPlaying = nil;
    self.artworkUrl = nil;
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
}

RCT_EXPORT_METHOD(updateNowPlayingInfo:(NSDictionary*)info)
{
    if (!self.nowPlaying)
    {
        return ;
    }

    for (NSString *key in info)
    {
        if ([key isEqualToString:MPMediaItemPropertyArtwork])
        {
            continue;
        }
        
        [self.nowPlaying setObject:info[key] forKey:key];
    }
    
    NSString *artworkUrl = info[MPMediaItemPropertyArtwork];

    if(artworkUrl && ![self.artworkUrl isEqualToString:artworkUrl])
    {
        self.artworkUrl = artworkUrl;
        [self.nowPlaying removeObjectForKey:MPMediaItemPropertyArtwork];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            UIImage *image = nil;
            
            if (!artworkUrl ||artworkUrl.length > 0)
            {
                if ([artworkUrl hasPrefix: @"http://"] || [artworkUrl hasPrefix:@"https://"])
                {
                    NSURL *imageURL = [NSURL URLWithString:artworkUrl];
                    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
                    image = [UIImage imageWithData:imageData];
                }
                else
                {
                    if ([[NSFileManager defaultManager] fileExistsAtPath:artworkUrl])
                    {
                        image = [UIImage imageNamed:artworkUrl];
                    }
                }
            }
            
            if (image)
            {
                CGImageRef cgref = [image CGImage];
                CIImage *cim = [image CIImage];
                
                if ( cgref || cim )
                {
                    dispatch_async(self.methodQueue, ^{
                        if ([artworkUrl isEqualToString:self.artworkUrl]) {
                            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
                            [self.nowPlaying setObject:artwork forKey:MPMediaItemPropertyArtwork];
                            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:self.nowPlaying];
                        }
                    });
                }
            }
        });
    }
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:self.nowPlaying];
}

RCT_EXPORT_METHOD(enableControl:(NSString*)controlName enabled:(BOOL)enabled)
{
    MPRemoteCommandCenter *rcc = [MPRemoteCommandCenter sharedCommandCenter];
    
    if ([controlName isEqualToString:REMOTE_CONTROL_PLAY])
    {
        rcc.playCommand.enabled = enabled;
    }
    else if ([controlName isEqualToString:REMOTE_CONTROL_PAUSE])
    {
        rcc.pauseCommand.enabled = enabled;
    }
    else if ([controlName isEqualToString:REMOTE_CONTROL_PREV])
    {
        rcc.previousTrackCommand.enabled = enabled;
    }
    else if ([controlName isEqualToString:REMOTE_CONTROL_NEXT])
    {
        rcc.nextTrackCommand.enabled = enabled;
    }
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initRemoteControl];
    }
    return self;
}

- (void)initRemoteControl
{
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [session setActive:YES error:nil];
    
    MPRemoteCommandCenter *rcc = [MPRemoteCommandCenter sharedCommandCenter];
    
    [rcc.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self sendEventWithName:EVENT_REMOTE_CONTROL_PLAY body:@{}];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [rcc.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self sendEventWithName:EVENT_REMOTE_CONTROL_PAUSE body:@{}];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [rcc.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self sendEventWithName:EVENT_REMOTE_CONTROL_PREV body:@{}];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [rcc.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self sendEventWithName:EVENT_REMOTE_CONTROL_NEXT body:@{}];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    rcc.playCommand.enabled = YES;
    rcc.pauseCommand.enabled = YES;
    rcc.previousTrackCommand.enabled = NO;
    rcc.nextTrackCommand.enabled = NO;
}

@end
