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;

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 ((placeholder.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    placeholder.Children.Add(new Controls.Adverts.CommentAdvert());
                placeholder.Children.Add(new CommentCard(comment));
            }
        }

        public void RemoveComment(CommentCard commentCard, string topCommentId = null)
        {
            if (string.IsNullOrWhiteSpace(topCommentId))
                placeholder.Children.Remove(commentCard);
            else
                (placeholder.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.Show();

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

            placeholder.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)
                placeholder.Children.Add(new CommentCard(comment));

            more.Complete();
        }

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

            more.Show();

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

            placeholder.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)
                placeholder.Children.Add(new CommentCard(comment));

            more.Complete();
        }

        private async void send_Click(object sender, RoutedEventArgs e)
        {
            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();
                placeholder.Children.Insert(0, new CommentCard(response));
                newComment.Text = "";
                scroll.ChangeView(null, 0, null);
            }
            catch { await new MessageDialog("Failed to publish your comment. Please, try again later.").ShowAsync(); }

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

        private async void ShowMore_Clicked()
        {
            request.PageToken = token;
            var response = await request.ExecuteAsync();

            foreach (CommentThread comment in response.Items)
            {
                if ((placeholder.Children.Count - 5) % 20 == 0 && !SecretsVault.AdsDisabled)
                    placeholder.Children.Add(new Controls.Adverts.CommentAdvert());
                placeholder.Children.Add(new CommentCard(comment));
            }
            
            token = response.NextPageToken;
            more.Complete();
            if (string.IsNullOrWhiteSpace(token))
                more.Visibility = Visibility.Collapsed;
        }
    }
}
