using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace ControlExplorer.Controls.RichTextBox
{
    public partial class FacebookRSS : UserControl
    {
        private const string FACEBOOK_RSS = "http://www.facebook.com/feeds/page.php?id=131214763781&format=atom10";
        private const string NAMESPACE = "http://www.w3.org/2005/Atom";
        private FriendlyDateTimeConverter _fdc;


        public FacebookRSS()
        {
            InitializeComponent();
            _fdc = new FriendlyDateTimeConverter();
            GetFacebookFeedItems();
        }

        public void GetFacebookFeedItems()
        {
            DownloadStringAsync(FACEBOOK_RSS);
        }

        private async Task DownloadStringAsync(string rss)
        {
            try
            {
                var client = HttpWebRequest.CreateHttp(rss);
                var response = await client.GetResponseAsync();
                var result = XElement.Load(response.GetResponseStream());
                var feeds = from entry in result.Elements("{" + NAMESPACE + "}entry") select entry;

                // build html content
                string html = "";
                foreach (XElement xe in feeds)
                {
                    html += xe.Element(XName.Get("content", NAMESPACE)).Value;
                    html += "<br/><span style='color: #9C9A9C'>Posted ";
                    string published = xe.Element(XName.Get("published", NAMESPACE)).Value;
                    DateTimeOffset dateOffset;
                    if (DateTimeOffset.TryParse(published, out dateOffset))
                    {
                        html += _fdc.Convert(dateOffset.UtcDateTime, typeof(string), null, null);
                    }
                    html += " by ComponentOne</span><br/>===============================<br/>";
                }

                // set total html to C1RTB
                c1RichTextBox1.Html = html;

                // collapse progress bar
            }
            catch
            {
                var dialog = new MessageDialog("Facebook RSS down at the moment. Try again later.");
                dialog.ShowAsync();
            }
            finally
            {
                c1ProgressBar1.Visibility = Visibility.Collapsed;
            }
        }

        private async void c1RichTextBox1_RequestNavigate(object sender, C1.Xaml.RichTextBox.RequestNavigateEventArgs e)
        {
            if (e.Hyperlink.NavigateUri.IsAbsoluteUri)
            {
                await Launcher.LaunchUriAsync(e.Hyperlink.NavigateUri);
            }
            else
            {
                // handle relative facebook urls
                await Launcher.LaunchUriAsync(new Uri("http://www.facebook.com" + e.Hyperlink.NavigateUri.OriginalString));
            }
        }
    }

    /// <summary>
    /// Converts a DateTime value to a friendly string like "8 hours ago" using UTC time
    /// </summary>
    public class FriendlyDateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value != null && value.GetType().Equals(typeof(DateTime)))
            {
                string totalTime = "";
                TimeSpan ts = DateTime.UtcNow - (DateTime)value;

                if (ts.Days > 1)
                {
                    totalTime = totalTime + ts.Days.ToString() + " days ";
                }
                else if (ts.Days == 1)
                {
                    totalTime = totalTime + "1 day ";
                }
                else
                {
                    if (ts.Hours > 1)
                    {
                        totalTime = totalTime + ts.Hours.ToString() + " hours ";
                    }
                    else if (ts.Hours == 1)
                    {
                        totalTime = totalTime + "1 hour ";
                    }
                    else
                    {
                        totalTime = totalTime + ts.Minutes.ToString() + " mins ";
                    }
                }

                totalTime = totalTime + "ago";
                return totalTime;
            }
            else
            {
                return value.ToString();
            }
        }
    }
}
