using C1.Xaml.Tile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace ControlExplorer.Controls.Tile
{
    public class FlickrPhoto : C1.Xaml.Tile.ILoadable
    {
        public string Title { get; set; }
        public string Thumbnail { get; set; }
        public string Content { get; set; }
        public string Author { get; set; }
        public ImageSource ImageSource { get; private set; }

        #region ** ILoadable implementation
        public bool IsLoaded
        {
            get { return _isLoaded; }
        }
        private bool _isLoaded = false;
        private FrameworkElement _imagePlaceHolder;

        public bool Load()
        {
            if (!_isLoaded && !string.IsNullOrEmpty(Thumbnail))
            {
                BitmapImage img = new BitmapImage(new Uri(Thumbnail, UriKind.Absolute));
                //img.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                img.ImageOpened += (s, e) =>
                {
                    _isLoaded = true;
                };
                img.ImageFailed += (s, e) =>
                {
                    _isLoaded = true;
                };
                // image can't be preloaded while it is not a part of the visual tree.
                // so place it into some element (even invisible) to force loading
                ImageBrush image = new ImageBrush();
                image.ImageSource = img;
                if (_imagePlaceHolder is Border)
                {
                    ((Border)_imagePlaceHolder).Background = image;
                }
                else
                {
                    Control rootFrame = Window.Current.Content as Control;
                    rootFrame.Background = image;
                }
                ImageSource = img;
            }
            return _isLoaded;
        }
        #endregion
        static string flickrUrl = "http://api.flickr.com/services/feeds/photos_public.gne";
        static string AtomNS = "http://www.w3.org/2005/Atom";

        /// <summary>
        /// Loads public photos from flickr.
        /// </summary>
        /// <param name="tag">If set, method uses it to load photos only with this specific tag.</param>
        /// <returns></returns>
        public static async Task Load(string tag, Control control)
        {

            List<FlickrPhoto> result = new List<FlickrPhoto>();
            Panel parentPanel = C1.Xaml.VTreeHelper.GetParentOfType(control, typeof(Panel)) as Panel;
            FrameworkElement placeholder = null;
            if (parentPanel != null)
            {
                placeholder = parentPanel.Tag as FrameworkElement;
                if (placeholder == null)
                {
                    placeholder = new Border();
                    placeholder.Visibility = Visibility.Collapsed;
                    parentPanel.Tag = placeholder;
                }
            }

            string uri = string.IsNullOrEmpty(tag) ? flickrUrl : flickrUrl + "?tags=" + tag;
            var client = HttpWebRequest.CreateHttp(uri);
            try
            {
                #region ** parse flickr data
                var response = await client.GetResponseAsync();
                var doc = XDocument.Load(response.GetResponseStream());
                foreach (var entry in doc.Descendants(XName.Get("entry", AtomNS)))
                {
                    var title = entry.Element(XName.Get("title", AtomNS)).Value;
                    var author = entry.Element(XName.Get("author", AtomNS)).Element(XName.Get("name", AtomNS)).Value;
                    var enclosure = entry.Elements(XName.Get("link", AtomNS)).Where(elem => elem.Attribute("rel").Value == "enclosure").FirstOrDefault();
                    var contentUri = enclosure.Attribute("href").Value;
                    result.Add(new FlickrPhoto() { Title = title, Content = contentUri, Thumbnail = contentUri.Replace("_b", "_m"), Author = author, _imagePlaceHolder = placeholder });
                }
                if (control is C1Tile)
                {
                    ((C1Tile)control).ContentSource = result;
                }
                else if (control is ItemsControl)
                {
                    ((ItemsControl)control).ItemsSource = result;
                }
                #endregion
            }
            catch
            {
                var dialog = new MessageDialog("There was an error when attempting to download data from Flickr.");
                dialog.ShowAsync();
            }
        }
    }
}
