using FoxTube.Controls;
using Microsoft.AppCenter.Analytics;
using System;
using System.Collections.Generic;
using Windows.System;
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
    {
        List<string> entries;
        int page = 1;
        public string id = "HL";

        public History()
        {
            InitializeComponent();
        }

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

            loading.RefreshPage += Refresh_Click;

            if (!string.IsNullOrWhiteSpace(e.Parameter.ToString()))
                id = e.Parameter.ToString();

            Initialize();
        }

        public async void Initialize()
        {
            try
            {
                loading.Refresh();

                entries = id == "HL" ? SecretsVault.History = await Methods.GetHistory() : SecretsVault.WatchLater = await Methods.GetLater();

                for (int k = 0; k < 25 && k < entries.Count; k++)
                    list.Add(new VideoCard(entries[k]));

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

                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("History loading error", new Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "ID", id }
                });
            }
        }

        private async void toBrowser_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri(id == "HL" ? "https://www.youtube.com/feed/history" : "https://www.youtube.com/playlist?list=WL"));
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            list.Clear();
            Initialize();
        }

        private void ShowMore_Clicked()
        {
            for (int k = 25 * page++; k < 25 * page; k++)
                list.Add(new VideoCard(entries[k]));

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