/// <summary>
        /// Gets the output file name with folder.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="rootPath">The root folder.</param>
        /// <returns>System.String.</returns>
        public static string GetMediaFileWithPath(this MediaStorageOptions self, string rootPath)
        {
            var isPhoto   = !(self is VideoMediaStorageOptions);
            var name      = (self != null) ? self.Name : null;
            var directory = (self != null) ? self.Directory : null;

            return(MediaFileHelpers.GetMediaFileWithPath(isPhoto, rootPath, directory, name));
        }
		internal MediaPickerDelegate (UIViewController viewController, UIImagePickerControllerSourceType sourceType, MediaStorageOptions options)
		{
			this.viewController = viewController;
			this.source = sourceType;
			this.options = options ?? new CameraMediaStorageOptions();

			if (viewController != null) {
				UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
				this.observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidRotate);
			}
		}
        /// <summary>
        /// Gets the unique filepath.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="rootPath">The root folder.</param>
        /// <param name="checkExists">The check exists.</param>
        /// <returns>System.String.</returns>
        public static string GetUniqueMediaFileWithPath(this MediaStorageOptions self, string rootPath,
                                                        Func <string, bool> checkExists)
        {
            var isPhoto = !(self is VideoMediaStorageOptions);
            var path    = self.GetMediaFileWithPath(rootPath);

            var folder = Path.GetDirectoryName(path);
            var name   = Path.GetFileNameWithoutExtension(path);

            return(MediaFileHelpers.GetUniqueMediaFileWithPath(isPhoto, folder, name, checkExists));
        }
 /// <summary>
 /// Verifies the options.
 /// </summary>
 /// <param name="self">The self.</param>
 /// <exception cref="System.ArgumentNullException">options</exception>
 /// <exception cref="System.ArgumentException">options.Directory must be a relative folder;options</exception>
 public static void VerifyOptions(this MediaStorageOptions self)
 {
     if (self == null)
     {
         throw new ArgumentNullException("options");
     }
     //if (!Enum.IsDefined (typeof(MediaFileStoreLocation), options.Location))
     //    throw new ArgumentException ("options.Location is not a member of MediaFileStoreLocation");
     //if (options.Location == MediaFileStoreLocation.Local)
     //{
     //if (String.IsNullOrWhiteSpace (options.Directory))
     //	throw new ArgumentNullException ("options", "For local storage, options.Directory must be set");
     if (Path.IsPathRooted(self.Directory))
     {
         throw new ArgumentException("options.Directory must be a relative folder", "options");
     }
     //}
 }
        /// <summary>
        /// Takes the media asynchronous.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="action">The action.</param>
        /// <param name="options">The options.</param>
        /// <returns>Task&lt;MediaFile&gt;.</returns>
        /// <exception cref="System.InvalidOperationException">Only one operation can be active at a time</exception>
        private Task<MediaFile> TakeMediaAsync(string type, string action, MediaStorageOptions options)
        {
            var id = GetRequestId();

            var ntcs = new TaskCompletionSource<MediaFile>(id);
            if (Interlocked.CompareExchange(ref _completionSource, ntcs, null) != null)
                throw new InvalidOperationException("Only one operation can be active at a time");

            _context.StartActivity(CreateMediaIntent(id, type, action, options));

            EventHandler<MediaPickedEventArgs> handler = null;
            handler = (s, e) =>
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);

                MediaPickerActivity.MediaPicked -= handler;

                if (e.RequestId != id)
                    return;

                if (e.Error != null)
                    tcs.SetException(e.Error);
                else if (e.IsCanceled)
                    tcs.SetCanceled();
                else
                    tcs.SetResult(e.Media);
            };

            MediaPickerActivity.MediaPicked += handler;

            return ntcs.Task;
        }
        /// <summary>
        /// Creates the media intent.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="type">The type.</param>
        /// <param name="action">The action.</param>
        /// <param name="options">The options.</param>
        /// <param name="tasked">if set to <c>true</c> [tasked].</param>
        /// <returns>Intent.</returns>
        private Intent CreateMediaIntent(int id, string type, string action, MediaStorageOptions options, bool tasked = true)
        {
            var pickerIntent = new Intent(_context, typeof (MediaPickerActivity));
            pickerIntent.PutExtra(MediaPickerActivity.EXTRA_ID, id);
            pickerIntent.PutExtra(MediaPickerActivity.EXTRA_TYPE, type);
            pickerIntent.PutExtra(MediaPickerActivity.EXTRA_ACTION, action);
            pickerIntent.PutExtra(MediaPickerActivity.EXTRA_TASKED, tasked);

            if (options != null)
            {
                pickerIntent.PutExtra(MediaPickerActivity.EXTRA_PATH, options.Directory);
                pickerIntent.PutExtra(MediaStore.Images.ImageColumns.Title, options.Name);

                var vidOptions = (options as VideoMediaStorageOptions);
                if (vidOptions != null)
                {
                    pickerIntent.PutExtra(MediaStore.ExtraDurationLimit, (int) vidOptions.DesiredLength.TotalSeconds);
                    pickerIntent.PutExtra(MediaStore.ExtraVideoQuality, (int) vidOptions.Quality);
                }
            }

            return pickerIntent;
        }
		private void VerifyOptions (MediaStorageOptions options)
		{
			if (options == null)
				throw new ArgumentNullException ("options");
			if (options.Directory != null && Path.IsPathRooted (options.Directory))
				throw new ArgumentException ("options.Directory must be a relative path", "options");
		}
		private static MediaPickerController SetupController (MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, MediaStorageOptions options = null)
		{
			var picker = new MediaPickerController (mpDelegate);
			picker.MediaTypes = new[] { mediaType };
			picker.SourceType = sourceType;

			if (sourceType == UIImagePickerControllerSourceType.Camera) {
				picker.CameraDevice = GetUICameraDevice ((options as CameraMediaStorageOptions) .DefaultCamera);

				if (mediaType == TypeImage)
					picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
				else if (mediaType == TypeMovie) {
					VideoMediaStorageOptions voptions = (VideoMediaStorageOptions)options;

					picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
					picker.VideoQuality = GetQuailty (voptions.Quality);
					picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
				}
			}

			return picker;
		}
		private Task<MediaFile> GetMediaAsync (UIImagePickerControllerSourceType sourceType, string mediaType, MediaStorageOptions options = null)
		{
			UIWindow window = UIApplication.SharedApplication.KeyWindow;
			if (window == null)
				throw new InvalidOperationException ("There's no current active window");

			UIViewController viewController = window.RootViewController;

			if (viewController == null) {
				window = UIApplication.SharedApplication.Windows.OrderByDescending (w => w.WindowLevel).FirstOrDefault (w => w.RootViewController != null);
				if (window == null)
					throw new InvalidOperationException ("Could not find current view controller");
				else
					viewController = window.RootViewController;	
			}

			while (viewController.PresentedViewController != null)
				viewController = viewController.PresentedViewController;

			MediaPickerDelegate ndelegate = new MediaPickerDelegate (viewController, sourceType, options);
			var od = Interlocked.CompareExchange (ref this.pickerDelegate, ndelegate, null);
			if (od != null)
				throw new InvalidOperationException ("Only one operation can be active at at time");

			var picker = SetupController (ndelegate, sourceType, mediaType, options);

			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary) {	
				ndelegate.Popover = new UIPopoverController (picker);
				ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate (ndelegate, picker);
				ndelegate.DisplayPopover();
			} else
				viewController.PresentViewController (picker, true, null);

			return ndelegate.Task.ContinueWith (t => {
				if (this.popover != null) {
					this.popover.Dispose();
					this.popover = null;
				}

				Interlocked.Exchange (ref this.pickerDelegate, null);
				return t;
			}).Unwrap();
		}