using FoxTube.Controls;
using Microsoft.AppCenter.Analytics;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.Resources;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace FoxTube.Pages
{
    /// <summary>
    /// YouTube history page
    /// </summary>
    public sealed partial class History : Page, INavigationPage
    {
        public object Parameter { get; set; } = null;
        int page = 1;
        int webPage = 0;

        public History()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            Parameter = e.Parameter;

            Initialize();
            Methods.MainPage.PageContent.LoadingPage.Close();
        }

        public async void Initialize()
        {
            Methods.MainPage.VideoContent.LoadingPage.Close();
            try
            {
                loading.Refresh();

                await Dispatcher.RunIdleAsync((command) =>
                {
                    for (int k = 0; k < 25 && k < HistorySet.Items.Count; k++)
                        list.Add(new VideoCard(HistorySet.Items[k].Id, "HL"));

                    if (list.Count >= HistorySet.Items.Count)
                        more.Visibility = Visibility.Collapsed;

                    if (list.Count == 0)
                        clear.Visibility = Visibility.Collapsed;
                });

                loading.Close();
            }
            catch (Exception e)
            {
                loading.Error(e.GetType().ToString(), e.Message);
                Analytics.TrackEvent("Local history loading error", new Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "StackTrace", e.StackTrace }
                });
            }
        }

        private async void toBrowser_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync("https://www.youtube.com/feed/history".ToUri());
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.PageContent.Refresh();
        }

        private async void ShowMore_Clicked()
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                for (int k = 25 * page++; k < 25 * page && k < HistorySet.Items.Count; k++)
                    list.Add(new VideoCard(HistorySet.Items[k].Id, "HL"));

                if (list.Count >= HistorySet.Items.Count)
                    more.Visibility = Visibility.Collapsed;
                else
                    more.Complete();
            });
        }

        private async void Clear_Click(object sender, RoutedEventArgs e)
        {
            ResourceLoader resources = ResourceLoader.GetForCurrentView("Playlist");
            MessageDialog dialog = new MessageDialog(resources.GetString("/Playlist/historyClear/Body"), resources.GetString("/Playlist/historyClear/Header"));
            dialog.Commands.Add(new UICommand(resources.GetString("/Playlist/no")));
            dialog.Commands.Add(new UICommand(resources.GetString("/Playlist/yes"), (command) => 
            {
                HistorySet.Clear();
                Refresh_Click(this, null);
            }));

            dialog.CancelCommandIndex = 0;
            dialog.DefaultCommandIndex = 1;
            await dialog.ShowAsync();
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(webPage == 0)
            {
                webPage++;
                LoadWeb();
            }
        }

        async void LoadWeb()
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                try
                {
                    websiteLoading.Refresh();

                    SecretsVault.History = await Methods.GetHistory();

                    for (int k = 0; k < 25 && k < SecretsVault.History.Count; k++)
                        websiteList.Add(new VideoCard(SecretsVault.History[k], "HL"));

                    if (websiteList.Count >= SecretsVault.History.Count)
                        websiteMore.Visibility = Visibility.Collapsed;

                    websiteLoading.Close();
                }
                catch (Exception e)
                {
                    websiteLoading.Error(e.GetType().ToString(), e.Message);
                    Analytics.TrackEvent("History loading error", new Dictionary<string, string>()
                    {
                        { "Exception", e.GetType().ToString() },
                        { "Message", e.Message },
                        { "StackTrace", e.StackTrace }
                    });
                }
            });
        }

        private async void WebsiteMore_Clicked()
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                for (int k = 25 * webPage++; k < 25 * webPage && k < SecretsVault.History.Count; k++)
                    websiteList.Add(new VideoCard(SecretsVault.History[k], "HL"));

                if (websiteList.Count >= SecretsVault.History.Count)
                    websiteMore.Visibility = Visibility.Collapsed;
                else
                    websiteMore.Complete();
            });
        }

        public void Delete (VideoCard item)
        {
            list.DeleteItem(item);
        }
    }
}
