using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation.Diagnostics;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace PhotoFilter
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class MainPage : Page
	{
		ConcurrentBag<ImageItem> m_images;
		public static ConcurrentBag<ImageDescriptor> _loadedImages = null;

		public MainPage()
		{
			this.InitializeComponent();
		}

		/// <summary>
		/// Invoked when this page is about to be displayed in a Frame.
		/// </summary>
		/// <param name="e">Event data that describes how this page was reached.  The Parameter
		/// property is typically used to configure the page.</param>
		protected override async void OnNavigatedTo(NavigationEventArgs e)
		{
			progressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
			if (_loadedImages == null)
			{
				_loadedImages = new ConcurrentBag<ImageDescriptor>();
				await LoadImages();
			}

			m_images = new ConcurrentBag<ImageItem>();
			foreach (var imageDescriptor in _loadedImages)
			{
				m_images.Add(await ImageItem.FromDescriptor(imageDescriptor));
			}

			var query = from image in m_images
						select image;
			groupInfoCVS.IsSourceGrouped = false;
			groupInfoCVS.Source = query;
			progressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
		}

		private async Task LoadImages()
		{
			m_images = new System.Collections.Concurrent.ConcurrentBag<ImageItem>();

			var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Images");
			var imageFiles = await folder.GetFilesAsync();
			foreach (var imageFile in imageFiles)
			{
				var image = new ImageItem(imageFile, ImageLocation.App);
				_loadedImages.Add(ImageCache.Instance.AddImage(image));
			}

			folder = Windows.Storage.KnownFolders.CameraRoll;
			imageFiles = await folder.GetFilesAsync();
			foreach (var imageFile in imageFiles)
			{
				var image = new ImageItem(imageFile, ImageLocation.CameraRoll);
				_loadedImages.Add(ImageCache.Instance.AddImage(image));
			}
		}
		private void pictureList_Tapped(object sender, TappedRoutedEventArgs e)
		{
			ListBox list = sender as ListBox;
			var imageItem = list.SelectedItem as ImageItem;
			var descriptor = imageItem.GetDescriptor();
			this.Frame.Navigate(typeof(ImagePage), list.SelectedItem);
			App.channel.LogMessage("Navigated to ImagePage", LoggingLevel.Information);
		}
	}
}
