//
// ImageChooser.m
//

#import "ImagePicker.h"

@interface ImagePicker ()
@property (nonatomic, strong) UIPopoverController * popover;
@end

@implementation ImagePicker

static NSString * CancelString;
static NSString * DeleteString;
static NSString * CameraString;
static NSString * PhotoLibraryString;

- (void)choose {
	[self choose:nil];
}

- (void)choose:(id)sender {
	
	if (!CancelString) {
		CancelString = NSLocalizedStringFromTable(@"Cancel",@"ImagePickerLocalized",0);
		DeleteString = NSLocalizedStringFromTable(@"Delete",@"ImagePickerLocalized",0);
		CameraString = NSLocalizedStringFromTable(@"Camera",@"ImagePickerLocalized",0);
		PhotoLibraryString = NSLocalizedStringFromTable(@"Photo Library",@"ImagePickerLocalized",0);
	}
	
	BOOL includeCameraInSources = self.shouldIncludeCameraInSources && [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
	BOOL includePhotoLibraryInSources = self.shouldIncludePhotoLibraryInSources && [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
	BOOL isDeletable = self.isDeletable;
	
	int numberOfOptions = 0;
	if (includeCameraInSources) numberOfOptions++;
	if (includePhotoLibraryInSources) numberOfOptions++;
	if (isDeletable) numberOfOptions++;

	
	if (numberOfOptions > 1 || isDeletable) {
		
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
		if (includeCameraInSources) {
			UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:CameraString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self chooseFromSource:UIImagePickerControllerSourceTypeCamera sender:sender];
			}];
			[alertController addAction:cameraAction];
		}
		if(includePhotoLibraryInSources) {
			UIAlertAction *photosAction = [UIAlertAction actionWithTitle:PhotoLibraryString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self chooseFromSource:UIImagePickerControllerSourceTypePhotoLibrary sender:sender];
			}];
			[alertController addAction:photosAction];
		}
		if(isDeletable) {
			UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:DeleteString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self deleteImage];
				return;
			}];
			[alertController addAction:deleteAction];
		}
		UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:CancelString style:UIAlertActionStyleDefault handler:nil];
		[alertController addAction:cancelAction];
		if ([sender isKindOfClass:[UIBarButtonItem class]]) {
		} else {
			[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
		}
		
	} else {
		if (includeCameraInSources) {
			[self chooseFromSource:UIImagePickerControllerSourceTypeCamera sender:sender];
		} else if (includePhotoLibraryInSources) {
			[self chooseFromSource:UIImagePickerControllerSourceTypePhotoLibrary sender:sender];
		}
	}
		
}

- (void)chooseFromSource:(UIImagePickerControllerSourceType)sourceType sender:(id)sender {
	
	//UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
	
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
	
	imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
	imagePickerController.sourceType = sourceType;
    imagePickerController.delegate = self;
	imagePickerController.allowsEditing = self.allowEditing;
	
	if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
		UIPopoverController * popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
		
		if ([sender isKindOfClass:[UIBarButtonItem class]]) {
			[popover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		}
		else if ([sender isKindOfClass:[UIView class]]) {
			[popover presentPopoverFromRect:((UIView *)sender).frame inView:((UIView *)sender).superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		}
		else {
			[popover presentPopoverFromRect:CGRectMake(0, 0, 200, 200) inView:self.viewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		}

		self.popover = popover;
	}
	else {
		[self.viewController presentViewController:imagePickerController animated:YES completion:nil];
	}

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	UIImage * originalImage = info[(id)UIImagePickerControllerOriginalImage];
	UIImage * editedImage = info[(id)UIImagePickerControllerEditedImage];
	
	UIImage * image;
	if (editedImage) image = editedImage;
	else image = originalImage;
	
	if (!self.editableObject || !self.editableObjectSaveKey.length) {
	}
	else {
		[self.editableObject setValue:UIImagePNGRepresentation(image) forKeyPath:self.saveKeyPath];
	}
	

	//NSLog(@"info: %@", info);
	if (self.popover) {
		[self.popover dismissPopoverAnimated:YES];
		self.popover = nil;
	}
	else {
		[picker dismissViewControllerAnimated:YES
								   completion:^{
									   
								   }];
	}

	
	//self.viewController.view.backgroundColor = [UIColor colorWithPatternImage:editedImage];
}

- (NSString *)saveKeyPath {
	return [NSString stringWithFormat:@"contents.%@", self.editableObjectSaveKey];
}

- (BOOL)isDeletable {
	if (!self.editableObject || !self.editableObjectSaveKey.length) return NO;
	id value = [self.editableObject valueForKeyPath:self.saveKeyPath];
	if (![value isKindOfClass:[NSData class]]) return NO;
	return [value length] > 0;
}

- (void)deleteImage {
	if (self.isDeletable) {
		[self.editableObject setValue:[NSData data] forKeyPath:self.saveKeyPath];
	}
}

@end
