using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Microsoft.AppCenter.Analytics;
using Microsoft.Toolkit.Uwp.UI.Controls;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using YoutubeExplode;

namespace FoxTube.Controls
{
    /// <summary>
    /// Playlist card control
    /// </summary>
    public sealed partial class PlaylistCard : UserControl
    {
        Playlist item;
        public string playlistId;

        public bool NeedInitialize { get; set; } = true;

        public PlaylistCard(string id)
        {
            InitializeComponent();
            Initialize(id);
        }

        public async void Initialize(string id)
        {
            try
            {
                playlistId = id;
                PlaylistsResource.ListRequest request = SecretsVault.Service.Playlists.List("snippet,contentDetails");
                request.Id = playlistId;
                request.Hl = SettingsStorage.RelevanceLanguage;
                item = (await request.ExecuteAsync()).Items[0];

                title.Text = item.Snippet.Localized.Title;
                channelName.Text = item.Snippet.ChannelTitle;
                counter.Text = item.ContentDetails.ItemCount.ToString();
                date.Text = Methods.GetAgo(item.Snippet.PublishedAt.Value);

                ChannelsResource.ListRequest r = SecretsVault.Service.Channels.List("snippet");
                r.Id = item.Snippet.ChannelId;

                var channelRequest = SecretsVault.Service.Channels.List("snippet");
                channelRequest.Id = item.Snippet.ChannelId;

                try
                {
                    thumbnail.Source = new BitmapImage(item.Snippet.Thumbnails.Medium.Url.ToUri());
                    avatar.ProfilePicture = new BitmapImage((await channelRequest.ExecuteAsync()).Items[0].Snippet.Thumbnails.Medium.Url.ToUri()) { DecodePixelHeight = 46, DecodePixelWidth = 46 };
                    //avatar.ProfilePicture = new BitmapImage((await new YoutubeClient().GetChannelAsync(item.Snippet.ChannelId)).LogoUrl.ToUri()) { DecodePixelWidth = 46, DecodePixelHeight = 46 };
                }
                catch { }

                show.Begin();
            }
            catch (Exception e)
            {
                (Parent as AdaptiveGridView)?.Items.Remove(this);
                Visibility = Visibility.Collapsed;
                Analytics.TrackEvent("PlaylistCard loading failed", new Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "Playlist ID", playlistId },
                    { "StackTrace", e.StackTrace }
                });
            }
        }

        public void Button_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.GoToPlaylist(item.Id);
        }

        private void OpenChannel_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.GoToChannel(item.Snippet.ChannelId);
        }

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

        private async void InBrowser_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync($"https://www.youtube.com/playlist?list={playlistId}".ToUri());
        }

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

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