#import "TMSavePhoto.h"
#import <UIKit/UIKit.h>

@interface TMSavePhoto ()
@property (nonatomic,copy) RCTResponseSenderBlock saveCallBack;
@end

@implementation TMSavePhoto

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


RCT_EXPORT_METHOD(savePhoto:(NSString *)imageUrl callback:(RCTResponseSenderBlock)callback) {
    self.saveCallBack = callback;
    
    if ([self validateUrl:imageUrl]) {
        dispatch_queue_t ioQueue = dispatch_queue_create("com.image.download", DISPATCH_QUEUE_SERIAL);
        dispatch_async(ioQueue, ^{
            NSURL *imageURL = [NSURL URLWithString:imageUrl];
            NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
            
            if (imageData) {
                UIImage *downloadImage = [UIImage imageWithData:imageData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImageWriteToSavedPhotosAlbum(downloadImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
                });
            }
        });
    }
}

//验证传入的imageUrl是否合法
- (BOOL)validateUrl:(NSString *)imageUrl {
    if (!imageUrl || imageUrl.length == 0) {
        if (self.saveCallBack) {
            self.saveCallBack(@[@"imageUrl参数为空"]);
        }
        return NO;
    }
    return YES;
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *message = !error ? @"成功保存图片到相册" : error.localizedDescription;
    
    if (self.saveCallBack) {
        self.saveCallBack(@[message]);
    }
}

@end
  
