namespace VideoDistanc
{
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using VideoDistanc.Web;
    using System.ServiceModel.DomainServices.Client;
    using System.Windows;
    using System.Linq;
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Windows.Input;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Home page for the application.
    /// </summary>
    public partial class Home : Page
    {
        /// <summary>
        /// Creates a new <see cref="Home"/> instance.
        /// </summary>

        private ChatContext _chatContext = new ChatContext();
        private LoadOperation<ChatList> getChat;
        private ChangeServiceReference.ChangeServiceClient client;
        private ChangeServiceReference.ChangeServiceClient changeSlide;
        private string user;

        public Home()
        {
            InitializeComponent();

            GetAllMessages();
            GetChange();
            TakeVisualization();
            ChangeImages();
        }

        //sleduje pasnou komunikace
        private void GetChange()
        {
            this.client = new ChangeServiceReference.ChangeServiceClient(
            new PollingDuplexHttpBinding { DuplexMode = PollingDuplexMode.MultipleMessagesPerPoll },
            new EndpointAddress("../ChangeService.svc"));

            this.client.NotifyReceived += new EventHandler<ChangeServiceReference.NotifyReceivedEventArgs>(client_NotifyReceived);
            this.client.SuscribeAsync("chat");
            
        }

        //udalost vyvolana tododou GetChange
        private void client_NotifyReceived(object sender, ChangeServiceReference.NotifyReceivedEventArgs e)
        {
            this.txtChat.Text += string.Format("{0}\n", e.Error != null ? e.Error.ToString() : e.message);
            this.txtChat.Select(this.txtChat.Text.Length - 1, 0);
        }

        //Nacteni dokumentu z databaze
        private void GetAllMessages()
        {
            getChat = _chatContext.Load(_chatContext.GetChatListsQuery());
            getChat.Completed += new EventHandler(getChat_Completed);
            
        }

        //udalost spustena pomoci medody GetAllMessages
        private void getChat_Completed(object sender, EventArgs e)
        {
            for (int i = 0; i < getChat.AllEntities.Count(); i++)
            {
                txtChat.Text += string.Format("{0} ({1}): {2}\n", getChat.Entities.ElementAt(i).Author, getChat.Entities.ElementAt(i).Time, getChat.Entities.ElementAt(i).Text);
                this.txtChat.Select(this.txtChat.Text.Length - 1, 0);
            }
        }

        //zmena zobrazeneho slidu
        private void ChangeImages()
        {
            this.changeSlide = new ChangeServiceReference.ChangeServiceClient(
            new PollingDuplexHttpBinding { DuplexMode = PollingDuplexMode.MultipleMessagesPerPoll },
            new EndpointAddress("../ChangeService.svc"));

            this.changeSlide.NotifyReceived += new EventHandler<ChangeServiceReference.NotifyReceivedEventArgs>(changeSlide_NotifyReceived);
            this.changeSlide.SuscribeAsync("slide");
        }
        //udalost z ChangeImages
        private void changeSlide_NotifyReceived(object sender, ChangeServiceReference.NotifyReceivedEventArgs e)
        {
            string uriAdress = "/Images/" + string.Format("{0}\n", e.Error != null ? e.Error.ToString() : e.message);
            image.Source = new BitmapImage(new Uri(uriAdress, UriKind.Relative));
        }
        
        //spusteni videa ze serveru
        private void TakeVisualization()
        {
            string uriAdress = "http://192.168.1.1:4653/Publishing";
            mediaElement.Source = new Uri(uriAdress, UriKind.Absolute);
            mediaElement.Play();
        }

        //odeslani zpravy a ulozeni do databaze
        private void Odeslat()
        {
            if (this.txtMyChat.Text != "")
            {
                //zapsání zprávy do databáze
                ChatList m = new ChatList();
                m.Author = user;
                m.Text = this.txtMyChat.Text;
                _chatContext.ChatLists.Add(m);
                _chatContext.SubmitChanges();

                //odeslání zprávy přes WCF všem uživatelům
                string mes = user + " (" + ActualTime() + "): " + this.txtMyChat.Text;
                this.client.PublishAsync(mes);
                this.txtChat.Text += string.Format(mes + "\n");
                this.txtChat.Select(this.txtChat.Text.Length - 1, 0);
                
                //vymazání řádku se zprávou
                this.txtMyChat.Text = "";
            }

        }


        //metoda pro načtění aktuálního času ve tvaru HH:MM:SS
        private string ActualTime()
        {
            TimeSpan timeNow = DateTime.Now.TimeOfDay;
            TimeSpan trimmedTimeNow = new TimeSpan(timeNow.Hours, timeNow.Minutes, timeNow.Seconds);
            return trimmedTimeNow.ToString();
        }

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>

                       
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            Odeslat();
        }

        private void txtMyChat_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Odeslat();
            }
        }

        
        private void LayoutRoot_LayoutUpdated(object sender, EventArgs e)
        {
            if (WebContext.Current.User.IsAuthenticated)
            {
                user = WebContext.Current.User.DisplayName;
                LayoutRoot.Visibility = System.Windows.Visibility.Visible;
            }
            else LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            txtMyChat.Text = "";
        }

        private void imageListDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            txtChat.Text = "";
            GetAllMessages();
        }
    }
}