using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Google.Apis.YouTube.v3;
using Microsoft.EntityFrameworkCore;

namespace YTManager.Tasks
{
    public class FetchVideos
    {
        public static void run(string youtubechannelIDstr = "")
        {
            // YT API access key
            var youtubeService = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyCuIYkMc5SktlnXRXNaDf2ObX-fQvtWCnQ",
                ApplicationName = "testingapppp"
            });

            // Get all the channels to update.
            var ops = new DbContextOptionsBuilder<MediaDB>();
            ops.UseNpgsql(YTManager.Startup.dbstr);
            using (var dbcontext = new MediaDB(ops.Options)) {
                // Get all the potential relevant channels.
                List<Models.Channel> channels;
                if (youtubechannelIDstr == "")
                    channels = dbcontext.Channels.ToList();
                else
                    channels = dbcontext.Channels.Where(c => c.YTChannelID == youtubechannelIDstr).ToList();

                // Get all the most recent videos for each channel.
                channels.ForEach(ch => {
                    // Get channel videos from youtube.
                    var query = youtubeService.Search.List("snippet");
                    query.ChannelId = ch.YTChannelID;
                    query.Order = SearchResource.ListRequest.OrderEnum.Date;
                    query.MaxResults = 50;
                    var response = query.Execute();

                    // Get all videos which aren't already in the DB.
                    var notindb = response.Items
                        .Where(i => i.Id.Kind == "youtube#video")
                        .Where(i => !dbcontext.Videos.Any(dbvid => dbvid.YTVideoID == i.Id.VideoId))
                        .Select(newvid =>
                            new Models.Video {
                                Title = newvid.Snippet.Title,
                                Description = newvid.Snippet.Description,
                                YTVideoID = newvid.Id.VideoId,
                                Uploaded = newvid.Snippet.PublishedAt.GetValueOrDefault(),
                                AddedtoDB = DateTime.Now,
                                YTChannelID = newvid.Snippet.ChannelId,
                                Channel = ch,
                                ThumbnailURL = newvid.Snippet.Thumbnails.Medium.Url
                            }).ToList();

                    // Add all videos not already in the database over.
                    notindb.ForEach(newvid => dbcontext.Videos.Add(newvid));

                    // And save since we are done.
                    dbcontext.SaveChanges();
                });
            }
        }
    }
}