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

namespace FoxTube.Controls
{
    public class ChatMessage
    {
        public string Author => message.AuthorDetails.DisplayName;
        public TextBlock Message
        {
            get
            {
                TextBlock block = new TextBlock()
                {
                    IsTextSelectionEnabled = true,
                    VerticalAlignment = VerticalAlignment.Top,
                    TextWrapping = TextWrapping.WrapWholeWords
                };
                Methods.FormatText(ref block, message.Snippet.DisplayMessage);
                return block;                
            }
        }
        public string ChannelId => message.AuthorDetails.ChannelId;
        public string Avatar => message.AuthorDetails.ProfileImageUrl;

        public Visibility IsVerified => message.AuthorDetails.IsVerified.Value ? Visibility.Visible : Visibility.Collapsed;
        public Visibility IsOwner => message.AuthorDetails.IsChatOwner.Value ? Visibility.Visible : Visibility.Collapsed;
        public Visibility IsSponsor => message.AuthorDetails.IsChatSponsor.Value ? Visibility.Visible : Visibility.Collapsed;
        public Visibility IsModerator => message.AuthorDetails.IsChatModerator.Value ? Visibility.Visible : Visibility.Collapsed;

        public Brush Background
        {
            get
            {
                if (IsVerified == Visibility.Visible || IsOwner == Visibility.Visible || IsSponsor == Visibility.Visible || IsModerator == Visibility.Visible)
                    return new SolidColorBrush() { Color = Colors.Red, Opacity = .2 };
                else
                    return new SolidColorBrush();
            }
        }
        public Thickness BorderThickness
        {
            get
            {
                if (IsVerified == Visibility.Visible || IsOwner == Visibility.Visible || IsSponsor == Visibility.Visible || IsModerator == Visibility.Visible)
                    return new Thickness(2);
                else
                    return new Thickness(0);
            }
        }

        private LiveChatMessage message;

        public ChatMessage(LiveChatMessage item)
        {
            message = item;
        }
    }

    public sealed partial class Chat : UserControl
    {
        string chatId;
        DateTime lastInsert;

        LiveChatMessagesResource.ListRequest request;
        LiveChatMessageListResponse response;

        DispatcherTimer timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromSeconds(1)
        };

        public Chat(string id)
        {
            InitializeComponent();
            if (!SecretsVault.IsAuthorized)
                inputField.Visibility = Visibility.Collapsed;
            chatId = id;

            request = SecretsVault.Service.LiveChatMessages.List(chatId, "snippet,authorDetails");

            timer.Tick += Update;
            timer.Start();
        }

        public async void Update(object sender, object e)
        {
            response = await request.ExecuteAsync();
            foreach (LiveChatMessage i in response.Items.FindAll(i => i.Snippet.PublishedAt >= lastInsert))
                list.Items.Insert(0, new ChatMessage(i));

            lastInsert = DateTime.Now;
            timer.Interval = TimeSpan.FromMilliseconds(response.PollingIntervalMillis.Value);
            timer.Start();
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            Methods.MainPage.GoToChannel(((HyperlinkButton)sender).Tag as string);
        }

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

                newMessage.IsEnabled = false;
                send.IsEnabled = false;
                
                LiveChatMessage message = new LiveChatMessage()
                {
                    Snippet = new LiveChatMessageSnippet()
                    {
                        Type = "textMessageEvent",
                        LiveChatId = chatId,
                        TextMessageDetails = new LiveChatTextMessageDetails()
                        {
                            MessageText = newMessage.Text
                        }
                    }
                };

                LiveChatMessagesResource.InsertRequest request = SecretsVault.Service.LiveChatMessages.Insert(message, "snippet,authorDetails");
                LiveChatMessage response = await request.ExecuteAsync();

                if(response != null)
                {
                    newMessage.Text = string.Empty;
                    list.Items.Add(new ChatMessage(response));
                }
            }
            catch(Exception e)
            {
                await new MessageDialog(ResourceLoader.GetForCurrentView("Chat").GetString("/Chat/failed")).ShowAsync();
                Analytics.TrackEvent("Failed to send a chat message", new Dictionary<string, string>()
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message }
                });
            }

            newMessage.IsEnabled = true;
            send.IsEnabled = true;
        }
    }
}
