using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using FoxTube.Controls;
using Windows.UI.Popups;
using Windows.ApplicationModel.Resources;
using Microsoft.AppCenter.Analytics;
using System.Collections.Generic;

namespace FoxTube.Pages
{
    /// <summary>
    /// Comments placeholder
    /// </summary>
    public sealed partial class CommentsPage : Page
    {
        ResourceLoader resources = ResourceLoader.GetForCurrentView("CommentsPage");

        string threadId;
        string token;

        CommentThreadsResource.ListRequest.OrderEnum order = CommentThreadsResource.ListRequest.OrderEnum.Relevance;
        CommentThreadsResource.ListRequest request;

        public CommentsPage()
        {
            InitializeComponent();
        }

        public async void Initialize(Video video)
        {
            threadId = video.Id;
            Methods.CommentsPage = this;

            if (!SecretsVault.IsAuthorized)
                grid.RowDefinitions[0].Height = new GridLength(0);

            counter.Text = $"{video.Statistics.CommentCount:0,0} {resources.GetString("/CommentsPage/comments")}";
            orderBtn.Content = resources.GetString("/CommentsPage/relevance/Text");

            request = SecretsVault.Service.CommentThreads.List("snippet,replies");
            request.MaxResults = 25;
            request.Order = order;
            request.VideoId = video.Id;
            request.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText;

            var response = await request.ExecuteAsync();

            token = response.NextPageToken;
            if (string.IsNullOrWhiteSpace(token))
                more.Visibility = Visibility.Collapsed;

            foreach (CommentThread comment in response.Items)
            {
                if ((list.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    list.Children.Add(new Controls.Adverts.CommentAdvert());
                list.Children.Add(new CommentCard(comment));
            }
        }

        public void RemoveComment(CommentCard commentCard, string topCommentId = null)
        {
            if (string.IsNullOrWhiteSpace(topCommentId))
                list.Children.Remove(commentCard);
            else
                (list.Children.Find(i => (i as CommentCard).thread.Id == topCommentId) as CommentCard)?.DeleteComment(commentCard);
        }

        private async void toRelevance_Click(object sender, RoutedEventArgs e)
        {
            if (order == CommentThreadsResource.ListRequest.OrderEnum.Relevance)
                return;

            more.Visibility = Visibility.Visible;

            order = CommentThreadsResource.ListRequest.OrderEnum.Relevance;
            orderBtn.Content = resources.GetString("/CommentsPage/relevance/Text");

            list.Children.Clear();
            
            request.Order = order;
            var response = await request.ExecuteAsync();

            token = response.NextPageToken;
            if (string.IsNullOrWhiteSpace(token))
                more.Visibility = Visibility.Collapsed;

            foreach (CommentThread comment in response.Items)
            {
                if ((list.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    list.Children.Add(new Controls.Adverts.CommentAdvert());
                list.Children.Add(new CommentCard(comment));
            }

            more.Complete();
        }

        private async void toDate_Click(object sender, RoutedEventArgs e)
        {
            if (order == CommentThreadsResource.ListRequest.OrderEnum.Time)
                return;

            more.Visibility = Visibility.Visible;

            order = CommentThreadsResource.ListRequest.OrderEnum.Time;
            orderBtn.Content = resources.GetString("/CommentsPage/publish");

            list.Children.Clear();

            request.Order = order;
            var response = await request.ExecuteAsync();

            token = response.NextPageToken;
            if (string.IsNullOrWhiteSpace(token))
                more.Visibility = Visibility.Collapsed;

            foreach (CommentThread comment in response.Items)
            {
                if ((list.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    list.Children.Add(new Controls.Adverts.CommentAdvert());
                list.Children.Add(new CommentCard(comment));
            }

            more.Complete();
        }

        private async void send_Click(object sender, RoutedEventArgs args)
        {
            if (string.IsNullOrWhiteSpace(newComment.Text))
                return;

            newComment.IsEnabled = false;
            send.IsEnabled = false;
            sending.Visibility = Visibility.Visible;

            CommentThread thread = new CommentThread
            {
                Snippet = new CommentThreadSnippet
                {
                    TopLevelComment = new Comment
                    {
                        Snippet = new CommentSnippet
                        {
                            TextOriginal = newComment.Text
                        }
                    },
                    VideoId = threadId
                }
            };

            try
            {
                CommentThread response = await SecretsVault.Service.CommentThreads.Insert(thread, "snippet").ExecuteAsync();
                list.Children.Insert(0, new CommentCard(response));
                newComment.Text = "";
                scroll.ChangeView(null, 0, null);
            }
            catch (Exception e)
            {
                await new MessageDialog("Failed to publish your comment. Please, try again later.").ShowAsync();
                Analytics.TrackEvent("Failed to post comment", new Dictionary<string, string>
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "Thread ID", threadId },
                    { "StackTrace", e.StackTrace }
                });
            }

            newComment.IsEnabled = true;
            send.IsEnabled = true;
            sending.Visibility = Visibility.Collapsed;
        }

        private async void ShowMore_Clicked()
        {
            request.PageToken = token;
            var response = await request.ExecuteAsync();
            
            token = response.NextPageToken;
            if (string.IsNullOrWhiteSpace(token))
                more.Visibility = Visibility.Collapsed;

            foreach (CommentThread comment in response.Items)
            {
                if ((list.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    list.Children.Add(new Controls.Adverts.CommentAdvert());
                list.Children.Add(new CommentCard(comment));
            }

            more.Complete();
        }
    }
}
