//
//  RDSImagePicker.m
//  SmartLightForBigFish
//
//  Created by coderYK on 2017/8/19.
//  Copyright © 2017年 RD. All rights reserved.
//

#import "RDSImagePicker.h"

@interface RDSImagePicker ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

/** 图片选择完成的回调*/
@property (nonatomic, copy) pickComplectBlock pickedBlock;
@property (nonatomic, assign) BOOL needEdit;

@end

@implementation RDSImagePicker

+ (instancetype)sharePicker {
    
    static RDSImagePicker *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (void)rds_pickImageFrom:(EImageSourceType)imgSourceType needEdit:(BOOL)need complected:(pickComplectBlock)pickComplectHandler {
    
    _pickedBlock = pickComplectHandler;
    _needEdit = need;
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
    pickerVC.delegate = self;
    pickerVC.allowsEditing = YES;
    pickerVC.sourceType = imgSourceType == EImageFromPhoto ? UIImagePickerControllerSourceTypeSavedPhotosAlbum : UIImagePickerControllerSourceTypeCamera;
    [keyWindow.rootViewController presentViewController:pickerVC animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *key = _needEdit ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage;
    UIImage *image = (UIImage *)info[key];
    //RDS_WEAKSELF(weakSelf)
    dispatch_async(dispatch_get_main_queue(), ^{
        if (image && self.pickedBlock) {
            self.pickedBlock(image);
            self.pickedBlock = nil;
        }
    });
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    //RDS_WEAKSELF(weakSelf)
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.pickedBlock) {
            self.pickedBlock(nil);
        }
    });
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
