using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Microsoft.Toolkit.Uwp.UI.Controls;
using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace FoxTube.Controls
{
    /// <summary>
    /// Channel item card
    /// </summary>
    public sealed partial class ChannelCard : UserControl
    {
        ResourceLoader resources = ResourceLoader.GetForCurrentView("Cards");

        string channelId;
        Channel item;

        public ChannelCard(string id, string live = null)
        {
            InitializeComponent();
            Initialize(id, live);
        }

        public async void Initialize(string id, string live)
        {
            try
            {
                if (id == SecretsVault.AccountId)
                    grid.RowDefinitions[3].Height = new GridLength(0);

                ChannelsResource.ListRequest request = SecretsVault.Service.Channels.List("snippet,statistics,brandingSettings");
                request.Id = id;
                ChannelListResponse response = await request.ExecuteAsync();

                item = response.Items[0];
                channelId = id;

                title.Text = item.Snippet.Title;
                description.Text = item.Snippet.Description;

                subs.Text = $"{item.Statistics.SubscriberCount:0,0} {resources.GetString("/Cards/subscribers")}";
                uploads.Text = $"{item.Statistics.VideoCount:0,0} {resources.GetString("/Cards/videos")}";

                if (live == "live")
                    liveTag.Visibility = Visibility.Visible;

                if (SecretsVault.IsAuthorized)
                {
                    if (SecretsVault.Subscriptions.Exists(i => i.Snippet.ResourceId.ChannelId == id))
                    {
                        subscribe.Background = new SolidColorBrush(Colors.Transparent);
                        subscribe.Foreground = new SolidColorBrush(Colors.Gray);
                        subscribe.Content = resources.GetString("/Cards/unsubscribe");
                    }
                    subscriptionPane.Visibility = Visibility.Visible;
                }

                try { avatar.ProfilePicture = new BitmapImage(new Uri(item.Snippet.Thumbnails.Medium.Url)) { DecodePixelWidth = 74, DecodePixelHeight = 74 }; }
                catch { }
                try
                {
                    if (!item.BrandingSettings.Image.BannerImageUrl.Contains("default"))
                        cover.Source = new BitmapImage(item.BrandingSettings.Image.BannerMobileImageUrl.ToUri());
                }
                catch { }
            }
            catch (Exception e)
            {
                (Parent as AdaptiveGridView)?.Items.Remove(this);
                Visibility = Visibility.Collapsed;
                Microsoft.AppCenter.Analytics.Analytics.TrackEvent("VideoCard loading failed", new System.Collections.Generic.Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "Video ID", id },
                    { "StackTrace", e.StackTrace }
                });
            }

            show.Begin();
        }

        public void Button_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.GoToChannel(channelId);
        }

        private void Hyperlink_Click(Windows.UI.Xaml.Documents.Hyperlink sender, Windows.UI.Xaml.Documents.HyperlinkClickEventArgs args)
        {
            SecretsVault.Authorize();
        }

        private async void subscribe_Click(object sender, RoutedEventArgs e)
        {
            if (await SecretsVault.ChangeSubscriptionState(channelId))
            {
                subscribe.Background = new SolidColorBrush(Colors.Transparent);
                subscribe.Foreground = new SolidColorBrush(Colors.Gray);
                subscribe.Content = resources.GetString("/Cards/unsubscribe");
            }
            else
            {
                subscribe.Background = new SolidColorBrush(Colors.Red);
                subscribe.Foreground = new SolidColorBrush(Colors.White);
                subscribe.Content = resources.GetString("/Cards/subscribe/Content");
            }
        }

        private void GetLink_Click(object sender, RoutedEventArgs e)
        {
            DataPackage data = new DataPackage();
            data.SetText($"https://www.youtube.com/channel/{item.Id}");
            Clipboard.SetContent(data);
        }

        private async void InBrowser_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync($"https://www.youtube.com/channel/{item.Id}".ToUri());
        }

        private void Cover_ImageOpened(object sender, RoutedEventArgs e)
        {
            showThumb.Begin();
        }

        private void Card_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Height = e.NewSize.Width * 0.75;
        }
    }
}
