using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Web.Syndication;

namespace FirstUniversalApp.ViewModels
{
	public class MainViewModel
	{
		public MainViewModel()
		{
			Items = new ObservableCollection<ItemViewModel>();
		}

		/// <summary>
		/// A collection for ItemViewModel objects.
		/// </summary>
		public ObservableCollection<ItemViewModel> Items { get; private set; }

		public bool IsDataLoaded
		{
			get;
			private set;
		}

		private const string FlickrRss = "http://api.flickr.com/services/feeds/photos_public.gne?tags={0}";

		/// <summary>
		/// Creates and adds a few ItemViewModel objects into the Items collection.
		/// </summary>
		public async Task LoadData()
		{
			await LoadData(string.Empty);
		}

		public async Task LoadData(string search)
		{
			SyndicationClient client = new SyndicationClient();
			SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri(string.Format(FlickrRss, search)));

			Items.Clear();

			foreach (SyndicationItem item in feed.Items)
			{
				Uri uri = (from link in item.Links where link.Relationship == "enclosure" select link.Uri).FirstOrDefault();
				ItemViewModel ivm = new ItemViewModel
									{
										ImageUri = uri, 
										Title = item.Title.Text, 
										Author = item.Authors[0].Name 
									};
				Items.Add(ivm);
			}

			IsDataLoaded = true;
		}
	}
}