using FoxTube.Controls;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Microsoft.AppCenter.Analytics;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

namespace FoxTube.Pages
{
    /// <summary>
    /// Playlist page
    /// </summary>
    public sealed partial class PlaylistPage : Page
    {
        public string playlistId;
        Playlist item;

        PlaylistItemsResource.ListRequest request;
        string token;

        public PlaylistPage()
        {
            InitializeComponent();

            DataTransferManager.GetForCurrentView().DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(Share);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.Parameter == null)
                loading.Error("NullReferenceException", "Unable to initialize page. Playlist ID is not stated.");
            else
                Initialize(e.Parameter as string);
        }

        public async void Initialize(string id)
        {
            loading.Refresh();

            try
            {
                playlistId = id;

                PlaylistsResource.ListRequest infoRequest = SecretsVault.Service.Playlists.List("snippet,contentDetails");
                infoRequest.Id = id;

                item = (await infoRequest.ExecuteAsync()).Items[0];

                title.Text = item.Snippet.Title;
                info.Text = $"{item.ContentDetails.ItemCount} {ResourceLoader.GetForCurrentView("Playlist").GetString("/Playlist/videos")}";
                description.Text = item.Snippet.Description;

                channelName.Text = item.Snippet.ChannelTitle;
                
                ChannelsResource.ListRequest channelRequest = SecretsVault.Service.Channels.List("snippet");
                channelRequest.Id = item.Snippet.ChannelId;
                Channel channel = (await channelRequest.ExecuteAsync()).Items[0];

                try { avatar.ProfilePicture = new BitmapImage(channel.Snippet.Thumbnails.Medium.Url.ToUri()); }
                catch { }
                try { thumbnail.Source = new BitmapImage(item.Snippet.Thumbnails.Medium.Url.ToUri()); }
                catch { }

                request = SecretsVault.Service.PlaylistItems.List("contentDetails");
                request.PlaylistId = id;
                request.MaxResults = 25;

                PlaylistItemListResponse response = await request.ExecuteAsync();
                token = response.NextPageToken;
                if (string.IsNullOrWhiteSpace(token))
                    more.Visibility = Visibility.Collapsed;
                
                foreach (PlaylistItem i in response.Items)
                    list.Add(new VideoCard(i.ContentDetails.VideoId, playlistId));

                loading.Close();
            }
            catch (System.Net.Http.HttpRequestException)
            {
                loading.Error("System.Net.Http.HttpRequestException", "Unable to connect to Google servers.", true);
            }
            catch (Exception e)
            {
                loading.Error(e.GetType().ToString(), e.Message);
                Analytics.TrackEvent("Playlist loading error", new Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "Playlist ID", playlistId }
                });
            }
        }

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

        private async void inBrowser_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri($"https://www.youtube.com/playlist?list={item.Id}"));
        }

        private void refresh_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.GoToPlaylist(playlistId);
        }

        private void share_Click(object sender, RoutedEventArgs e)
        {
            DataTransferManager.ShowShareUI();
        }

        private void Share(DataTransferManager sender, DataRequestedEventArgs args)
        {
            Methods.Share(args,
                item.Snippet.Thumbnails.Medium.Url,
                item.Snippet.Title,
                $"https://www.youtube.com/playlist?list={item.Id}",
                ResourceLoader.GetForCurrentView("Cards").GetString("/Cards/playlistShare"));
        }

        private async void ShowMore_Clicked()
        {
            request.PageToken = token;
            PlaylistItemListResponse response = await request.ExecuteAsync();

            if (string.IsNullOrWhiteSpace(request.PageToken))
                more.Visibility = Visibility.Collapsed;
            else
            {
                token = response.NextPageToken;
                more.Complete();
            }

            foreach (PlaylistItem i in response.Items)
                list.Add(new VideoCard(i.ContentDetails.VideoId, playlistId));
        }
    }
}
