using C1.Xaml.Tile;
using System;
using TileSamples.Data;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace TileSamples.Samples
{
    /// <summary>
    /// 
    /// </summary>
    public sealed partial class TwitterFeed : Page
    {
        // The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.
        // At least application-only authentication is required: https://dev.twitter.com/docs/auth/application-only-auth
        // We can't ship credentials with a sample, so perhaps we won't migrate this sample to API v1.1.

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

        private TimeSpan _storedUpdateInterval = C1TileService.UpdateInterval;

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // if we don't need too frequent updates here, increase update interval
            C1TileService.UpdateInterval = TimeSpan.FromSeconds(10);
            LoadContent();
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            // restore C1TileService update interval
            C1TileService.UpdateInterval = _storedUpdateInterval;
        }

        private async void LoadContent()
        {
            retry.Visibility = Visibility.Collapsed;
            try
            {
                // load twitter data from rss channels
                foreach (C1Tile tile in tilePanel.Children)
                {
                    var content = await FeedData.Load(string.Format(FeedData.Link, tile.Header));
                    tile.ContentTemplateSelector = Resources["TileContentSelector"] as DataTemplateSelector;
                    tile.ContentSource = content;
                }
            }
            catch
            {
                var dialog = new Windows.UI.Popups.MessageDialog("There was an error when attempting to download data from Twitter.");
                dialog.ShowAsync();
                retry.Visibility = Visibility.Visible;
            }
        }

        private void Retry_Click(object sender, RoutedEventArgs e)
        {
            LoadContent();
        }

        private async void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            var link = new Uri((string)(sender as HyperlinkButton).Content);
            if (link != null)
            {
                await Windows.System.Launcher.LaunchUriAsync(link);
            }
        }
    }

    public class TileTemplateSelector : DataTemplateSelector
    {

        public ResourceDictionary Resources { get; set; }

        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            DataTemplate result = null;
            C1Tile tile = container as C1Tile;
            ContentPresenter cp = C1.Xaml.VTreeHelper.GetChildOfType(tile, typeof(ContentPresenter)) as ContentPresenter;
            DataTemplate backContentTemplate = Resources["BackContentTemplate"] as DataTemplate;
            if (tile.Content is Grid || cp == null || cp.ContentTemplate == backContentTemplate)
            {
                // show corresponding feed icon
                result = Resources[tile.Header] as DataTemplate;
            }
            else 
            {
                // show twit
                result = backContentTemplate;
            }
            return result ?? base.SelectTemplateCore(item, container);
        }
    }
}
