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;

namespace FoxTube
{
    public static class DownloadAgent
    {
        public static List<DownloadItem> items = new List<DownloadItem>();
        private static 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);
            try
            {
                List<DownloadItemContainer> containers = JsonConvert.DeserializeObject<List<DownloadItemContainer>>((string)settings.Values["downloads"]);
                containers.ForEach(i => items.Add(new DownloadItem(i)));
            }
            catch { }
        }

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

        public static void Remove(DownloadItem item)
        {
            try { Page.Remove(item); }
            catch { }
            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;
        }
    }
}
