﻿using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Xaml.Controls;

namespace JustRemember.Helpers
{
	static public class ContentDialogExtensions
	{
		static public async Task<ContentDialogResult> EnqueueAndShowIfAsync(this ContentDialog contentDialog, Func<bool> predicate = null)
		{
			TaskCompletionSource<bool?> currentDialogCompletion = new TaskCompletionSource<bool?>();
			TaskCompletionSource<bool?> previousDialogCompletion = null;

			// No locking needed since we are always on the UI thread.
			if (!CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess) { throw new NotSupportedException("Can only show dialog from UI thread."); }
			previousDialogCompletion = PreviousDialogCompletion;
			PreviousDialogCompletion = currentDialogCompletion;

			if (previousDialogCompletion != null)
			{
				await previousDialogCompletion.Task;
			}
			var whichButtonWasPressed = ContentDialogResult.None;
			if (predicate == null || predicate())
			{
				whichButtonWasPressed = await contentDialog.ShowAsync();
			}
			currentDialogCompletion.SetResult(null);
			return whichButtonWasPressed;
		}

		static private TaskCompletionSource<bool?> PreviousDialogCompletion = null;
	}
}
