
#import "RNAvplayer.h"
#import <React/RCTLog.h>
#import <AVFoundation/AVFoundation.h>

#if __has_include("RCTUtils.h")
    #import "RCTUtils.h"
#else
    #import <React/RCTUtils.h>
#endif

@implementation RNAvplayer {
    AVPlayer* player;
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(prepare:(NSString*)stringUrl withOptions:(NSDictionary*)options withCallback:(RCTResponseSenderBlock)callback)
{
    if(!([stringUrl length] > 0)){
        return callback(@[@{@"error": @"url cannot be empty"}]);
    }
    
    
    @try {
        NSURL* url = [NSURL URLWithString:stringUrl];
        NSMutableDictionary* headers = [NSMutableDictionary dictionary];
        
        for(NSString* key in options) {
            NSString value = [options objectForKey:key];
        }
        
        [headers setObject:@"Your UA" forKey:@"User-Agent"];
        AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:@{@"AVURLAssetHTTPHeaderFieldsKey" : headers}];
        AVPlayerItem* item = [AVPlayerItem playerItemWithAsset:asset];
        player = [[AVPlayer alloc] initWithPlayerItem:item];
        
        if(player) {
            player.delegate = self;
            player.enableRate = YES;
            [player prepareToPlay];
            callback(@[[NSNull null], @{@"duration": @(player.duration)}]);
        }
    }
    @catch(NSException* exception) {
        NSError* error = [NSError initWithDomain:@"com.AVPLAYER.ios" code:1 userInfo:exception.reason]
        callback(@[RCTJSErrorFromNSError(error)]);
    }

}

RCT_EXPORT_METHOD(play:(RCTResponseSenderBlock)callback)
{
    RCTLogInfo(@"Logging: play");
}


@end
  
