using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Windows.Media.Imaging;
using System.Xml;
using FirstWP8App.Resources;

namespace FirstWP8App.ViewModels
{
	public class MainViewModel : INotifyPropertyChanged
	{
		public MainViewModel()
		{
			this.Items = new ObservableCollection<ItemViewModel>();
		}

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

		private string _sampleProperty = "Sample Runtime Property Value";
		/// <summary>
		/// Sample ViewModel property; this property is used in the view to display its value using a Binding
		/// </summary>
		/// <returns></returns>
		public string SampleProperty
		{
			get
			{
				return _sampleProperty;
			}
			set
			{
				if (value != _sampleProperty)
				{
					_sampleProperty = value;
					NotifyPropertyChanged("SampleProperty");
				}
			}
		}

		/// <summary>
		/// Sample property that returns a localized string
		/// </summary>
		public string LocalizedSampleProperty
		{
			get
			{
				return AppResources.SampleProperty;
			}
		}

		public bool IsDataLoaded
		{
			get;
			private set;
		}

		private static readonly 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 void LoadData()
		{
			LoadData(string.Empty);
		}

		public void LoadData(string search)
		{
            WebClient wc = new WebClient();
			wc.DownloadStringCompleted += wc_DownloadStringCompleted;
			wc.DownloadStringAsync(new Uri(string.Format(FlickrRss, search)));
		}

		void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			this.Items.Clear();

            StringReader sr = new StringReader(e.Result);
            XmlReader reader = XmlReader.Create(sr);
            SyndicationFeed feed = SyndicationFeed.Load(reader);

			int id = 0;

            foreach (SyndicationItem item in feed.Items)
			{
				Uri uri = (from link in item.Links where link.RelationshipType == "enclosure" select link.Uri).FirstOrDefault();
				ItemViewModel ivm = new ItemViewModel
									{
										ID = id++.ToString(),
										ImageUri = uri, 
										LineOne = item.Title.Text, 
										LineTwo = item.Authors[0].Name 
									};
				this.Items.Add(ivm);
			}

			this.IsDataLoaded = true;
		}

		public event PropertyChangedEventHandler PropertyChanged;
		private void NotifyPropertyChanged(String propertyName)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (null != handler)
			{
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}
}