using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Notifications;

namespace FoxTube.Background
{
    public sealed class BackgroundProcessor : IBackgroundTask
    {
        private DateTime lastCheck = DateTime.Now;
        private readonly ApplicationDataContainer settings = ApplicationData.Current.RoamingSettings;
        dynamic prefs;
        private readonly YouTubeService Service = new YouTubeService(new BaseClientService.Initializer()
        {
            ApiKey = "AIzaSyBgHrCnrlzlVmk0cJKL8RqP9Y8x6XSuk_0",
            ApplicationName = "FoxTube"
        });
        BackgroundTaskDeferral def;

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                def = taskInstance.GetDeferral();

                if (settings.Values["lastCheck"] == null)
                {
                    settings.Values["lastCheck"] = DateTime.Now.ToString();
                    def.Complete();
                    return;
                }
                else
                    lastCheck = DateTime.Parse(settings.Values["lastCheck"] as string);

                prefs = JsonConvert.DeserializeObject<dynamic>(settings.Values["settings"] as string);
                if ((bool)prefs.devNotifications)
                    CheckAnnouncements();
                if ((bool)prefs.videoNotifications)
                    await CheckAccount();
            }
            finally
            {
                settings.Values["lastCheck"] = DateTime.Now.ToString();
                def.Complete();
            }
        }

        async Task CheckAccount()
        {
            try
            {
                Dictionary<string, string> subscriptions = JsonConvert.DeserializeObject<Dictionary<string, string>>(settings.Values["subscriptions"] as string);

                List<SearchResult> results = new List<SearchResult>();

                foreach (var s in subscriptions)
                {
                    SearchResource.ListRequest request = Service.Search.List("snippet");
                    request.PublishedAfter = lastCheck;
                    request.ChannelId = s.Key;
                    request.Type = "video";
                    request.MaxResults = 5;
                    SearchListResponse response = await request.ExecuteAsync();

                    foreach (SearchResult i in response.Items)
                    {
                        results.Add(i);

                        ToastNotificationManager.CreateToastNotifier().Show(
                            Notification.GetVideoToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title, i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, s.Value));
                    }
                }

                results.OrderBy(i => i.Snippet.PublishedAt);

                TileUpdater updater = TileUpdateManager.CreateTileUpdaterForApplication();
                updater.EnableNotificationQueue(true);
                updater.Clear();
                for (int i = 0; i < 5 && i < results.Count; i++)
                    updater.Update(Tiles.GetTileLayout(System.Security.SecurityElement.Escape(results[i].Snippet.Title), System.Security.SecurityElement.Escape(results[i].Snippet.ChannelTitle), results[i].Snippet.Thumbnails.Medium.Url.Replace("&", "%26"), subscriptions[results[i].Snippet.ChannelId]));
            }
            catch { }
        }

        async void CheckAnnouncements()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(await new HttpClient().GetStringAsync("http://foxgame-studio.000webhostapp.com/foxtube-messages.xml"));
                XmlElement item = doc["posts"].FirstChild as XmlElement;

                DateTime date = DateTime.Parse(item.GetAttribute("time"));
                if (date > lastCheck && date < DateTime.Now)
                    ToastNotificationManager.CreateToastNotifier().Show(
                        Notification.GetInternalToast(item["id"].InnerText,
                        item["header"][(string)prefs.language].InnerText,
                        item["content"][(string)prefs.language].InnerText,
                        item["thumbnail"].InnerText,
                        item["avatar"].InnerText));
            }
            catch { }
        }
    }
}
