using System;
using System.Collections.Generic;
using Windows.Storage;
using Newtonsoft.Json;
using YoutubeExplode.Models.MediaStreams;
using Google.Apis.YouTube.v3.Data;
using FoxTube.Controls;
using FoxTube.Pages;
using Microsoft.AppCenter.Analytics;

namespace FoxTube
{
    public static class DownloadAgent
    {
        public static List<DownloadItem> Items { get; set; } = new List<DownloadItem>();
        private static readonly ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
        public static Downloads Page { get; set; }
        public static StorageFolder Downloads { get; set; }

        public static async void Initialize()
        {
            Downloads = await KnownFolders.VideosLibrary.CreateFolderAsync("FoxTube", CreationCollisionOption.OpenIfExists);
            Items.Clear();
            try
            {
                List<DownloadItemContainer> containers = JsonConvert.DeserializeObject<List<DownloadItemContainer>>((string)settings.Values[$"downloads"]);
                containers.ForEach(i => Items.Add(new DownloadItem(i)));
            }
            catch (Exception e)
            {
                settings.Values["downloads"] = JsonConvert.SerializeObject(new List<DownloadItemContainer>());
                Analytics.TrackEvent("Failed to load downloads history", new Dictionary<string, string>
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "StackTrace", e.StackTrace }
                });
            }
        }

        public static void Add(MediaStreamInfo info, Video meta, string qualty)
        {
            Items.Insert(0, new DownloadItem(info, meta, qualty));
        }

        public static void Remove(DownloadItem item)
        {
            Page?.Remove(item);
            Items.Remove(item);
        }


        public static void Cancel(string id)
        {
            DownloadItem item = Items.Find(i => i.Container.Id == id);
            if (item != null)
                item.Cancel();
        }

        public static void QuitPrompt()
        {
            foreach (DownloadItem i in Items.FindAll(i => !i.Container.IsDownloaded))
            {
                i.Cancel();
                Items.Remove(i);
            }

            List<DownloadItemContainer> containers = new List<DownloadItemContainer>();
            Items.ForEach(i => containers.Add(i.Container));

            string data = JsonConvert.SerializeObject(containers);

            settings.Values[$"downloads"] = data;
        }
    }
}
