using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using BeWo.View;
using ChatController.ChatKlassen;
using ChatController.HauptKlassen;
using ChatController.Klassen;
using Path = System.IO.Path;

namespace ChatController
{
    /// <summary>
    /// Interaktionslogik für ChatMainWindow.xaml
    /// </summary>
    public partial class ChatMainControl : UserControl
    {
        #region Vokabeln 
        private Chat _chat;
        private AktuellerKontakt _aktuellerKontakt;

        private bool isChatBoxOnFocus = false;

        private ChatEmojiiControl _emojiView;

        private IOrderedEnumerable<ChatMessage> _Orderedmessagelist;
        private IOrderedEnumerable<KontaktlistBuilder> _kontaktlist;
        
        private ChatDatenUebergabe _chatDaten;

        private bool scrollPrueferAktivieren = false;

        public Thread newThread;
        public bool disableKontaktNachrichtenThread = true;

        public Thread AlleKontakteThread;
        public bool AlleNachrichtenThreadBool = true;
        private double? AlleNachrichtenCount = null;
        private List<String> createdTempFiles = new List<String>();

        private Dictionary<String, Action<string>> menuItemName2Callback = new Dictionary<string, Action<string>>();

        public delegate void CloseDelegate();

        public event CloseDelegate OnClose;

        private bool _isDesktopVersion = true;
        #endregion

        public ChatMainControl()
        {
            InitializeComponent();
            ReloadGruppen.Visibility = Visibility.Collapsed;
        }

        public void InitMitChatdaten(ChatDatenUebergabe cdu)
        {
            _chatDaten = cdu;
            _chat = new Chat(cdu);
            
            _kontaktlist = _chat.GroupklassenInChatKontakteUmwandler();

            Clientlist.ItemsSource = _kontaktlist;
         
            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
            view.Filter = UserFilter;          

            HorcheAlleGruppenNachrichten();
            LeseMessageInfoAusDatei();

            Clientlist.Items.Refresh();
        }
        
        public AktuellerKontakt GetAktuellenKontakt()
        {
            if (AktChatUserList != null)
            {
                var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];

                if (kontakt.CustomerOid == null)
                {
                    return null;
                }

                return kontakt;
            }
            else
            {
                return null;
            }
        }

        public List<ChatMessage> GetSelectedMessages()
        {
            List<ChatMessage> itemListe = new List<ChatMessage>();

            foreach (Object selecteditem in ChatListBox.SelectedItems)
            {
                ChatMessage Item = selecteditem as ChatMessage;

                //if (Item.MessagePersonOid == 0)
                //{
                    itemListe.Add(Item);
                //}
            }

            if(itemListe.Count > 0) { 

                return itemListe;
            }
            else
            {
                return null;
            }
        }

        #region Style setter für ownChatDesktop Version
        public void SetzteStyleAufNull()
        {
            EmojiButton.Style = null;
            MediaButton.Style = null;
            ReloadGruppen.Visibility = Visibility.Visible;
            _isDesktopVersion = false;
        }
        #endregion
        
        #region Lade KontaktDaten und Lade sie in den Chat
        private void AktChatUser_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            _chat.ShowKontaktPicture(_aktuellerKontakt);
        }

        private void Clientlist_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(Clientlist.SelectedItem != null)
            {
                // StartWaiting();
                disableKontaktNachrichtenThread = true;
                 Cursor = Cursors.Wait;
                scrollPrueferAktivieren = false;
                ChatListBox.ItemsSource = null;

                AktChatUserList.Items.Clear();

                var kontakt = (KontaktlistBuilder)Clientlist.SelectedItem;

                if(kontakt.SetzeGelesen == 1) { 
                    kontakt.SetzeGelesen = 0;

                    Clientlist.Items.Refresh();
                }

                var aktuellerKontakt = new AktuellerKontakt(kontakt);

                AktChatUserList.Items.Add(aktuellerKontakt);
                _aktuellerKontakt = aktuellerKontakt;

                var x = _chat.LadeChatNachrichtenVomKontakt(aktuellerKontakt);

                ChatListBox.ItemsSource = x;

                //ChatListBox.Items.MoveCurrentToLast();
                //ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);

                if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0)
                {
                    Border border = (Border)VisualTreeHelper.GetChild(ChatListBox, 0);
                    ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                    scrollViewer.ScrollToBottom();
                }

                //if (ChatListBox.Items.Count > 0)
                //{
                //    ChatListBox.SelectedIndex = ChatListBox.Items.Count - 1;
                //    ChatListBox.ScrollIntoView(ChatListBox.SelectedItem);
                //}

                ChatListBox.ContextMenu = _chat.ErstelleKontextMenue();
                SetContextHandler();
                scrollPrueferAktivieren = true;

                HorcheAktivNachNachrichten();
                Cursor = Cursors.Arrow;

               
                disableKontaktNachrichtenThread = false;
                // EndWaiting();
            }
        }
        #endregion

        #region Context Menue
        //ab Hier Kontext Menü
        private void SetContextHandler()
        {
            var contextItems = ChatListBox.ContextMenu.Items;

            foreach (var menuItemText in menuItemName2Callback.Keys)
            {
                var cb = menuItemName2Callback[menuItemText];

                MenuItem item = new MenuItem();

                item.Click += (s, e2) =>
                {
                    cb(menuItemText);
                };
                item.Header = menuItemText;

                contextItems.Add(item);
            }

            var item2 = (MenuItem)contextItems[0];
            item2.Click += Item2OnClick; // umbenenen in Speichern unter 
            var item3 = (MenuItem)contextItems[1];
            item3.Click += Item3OnClick; //Umbenenen in Einfügen 

            // neu und vor Einfügen setzen und anpassen
            var item4 = (MenuItem) contextItems[2];
            item4.Click += Item4OnClick; //Umbenenen in Kopieren
            
        }

        public delegate void ContextDelegate();

        public event ContextDelegate CreateNewContextItems;

        private void Item2OnClick(object sender, RoutedEventArgs routedEventArgs)
        {
            foreach (var items in ChatListBox.SelectedItems)
            {
                var item = (ChatMessage)items;

                _chat.SpeichernUnterFunkion(item);
            }
        }

        private void Item3OnClick(object sender, RoutedEventArgs routedEventArgs)
        {
            var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];
            _chat.Einfuegen(kontakt.GroupId,this);          
        }

        private void Item4OnClick(object sender, RoutedEventArgs routedEventArgs)
        { 
            string chatmessages = "";
            foreach (var items in ChatListBox.SelectedItems)
            {
                var item = (ChatMessage)items;

                chatmessages += item.UserMessage + "\n";
            }

            if(!chatmessages.Equals(""))
                _chat.Kopieren(chatmessages, 1);
        }

        private void Chat_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            var chatItems = ChatListBox.SelectedItems;

            if (chatItems.Count > 0)
            {
                foreach (var items in chatItems)
                {
                    var item = items as ChatMessage;
                    if (item != null && item.ImageSources != null)
                    {
                        var contextItems = ChatListBox.ContextMenu.Items;
                        var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
                        ContextItemSpeichernUnter.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        var contextItems = ChatListBox.ContextMenu.Items;
                        var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
                        ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
                    }

                    if (item.ImageSources == null && item.Dokpfad == null)
                    {
                        var contextItems = ChatListBox.ContextMenu.Items;
                        var ContextItemSpeichernUnter = (MenuItem) contextItems[2];
                        ContextItemSpeichernUnter.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        var contextItems = ChatListBox.ContextMenu.Items;
                        var ContextItemSpeichernUnter = (MenuItem)contextItems[2];
                        ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
                    }


                }
            }
            else
            {
                //Schalte speichern unter Aus 
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[0];
                ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
            }


            //prüfe ob was in dem Speicher vorhanden ist //Einfügen
            var d = System.Windows.Forms.Clipboard.GetDataObject();

            if (d.GetDataPresent(DataFormats.FileDrop))
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else if (d.GetDataPresent(DataFormats.Text))
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else if (d.GetDataPresent(DataFormats.Bitmap))
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
            }

            //prüfe ob dokumentation erlaubt
            var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];
            if (kontakt.CustomerOid == null && ChatListBox.ContextMenu.Items.Count > 3)
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
                ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
            }
            else if (ChatListBox.ContextMenu.Items.Count > 3)
            {
                var contextItems = ChatListBox.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[3];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            


            if (ChatListBox.ContextMenu.Items.Count == 0)
            {
                ChatListBox.ContextMenu.Visibility = Visibility.Collapsed;
            }

        }

        public void AddContextMenu(string menuItemText, Action<string> callBackAction)
        {
            if (!menuItemName2Callback.ContainsKey(menuItemText))
            {
                menuItemName2Callback.Add(menuItemText, callBackAction);
            }
        }
        #endregion

        #region Sende Media Nachrichten
        private void MediaButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (AktChatUserList.Items.Count > 0)
            {
                var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];
                
                var medium = _chat.HoleMedium();

                if(medium != null) {

                    string convertetMedia = _chat.ScaleImage(medium, Path.GetExtension(medium.ToUpperInvariant()));

                    if (!convertetMedia.Equals(""))
                    {
                        _chat.AddeMediumDerNachrichtView(convertetMedia,medium);

                        CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
                        ChatListBox.Items.MoveCurrentToLast();
                        ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);

                        _chat.SendeMediumAnKontakt(kontakt, convertetMedia,medium);

                        if (!convertetMedia.Equals("") && !convertetMedia.Equals(medium) && File.Exists(convertetMedia))
                        {
                            File.Delete(convertetMedia);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Die gewählte Datei ist zu groß!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                }
            }
            else
            {
                MessageBox.Show("Bitte wählen Sie einen Kontakt aus.","ownChat",MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        #endregion

        #region Sende Normale Nachrichten
        private void SendButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("") && isChatBoxOnFocus)
            {
                if (!Chatbox.Text.Equals(""))
                {
                    var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];
                     
                    _chat.AddeNachrichtDerView(Chatbox.Text);
                    
                    CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();

                    ChatListBox.Items.MoveCurrentToLast();
                    ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
                    
                    _chat.SendMessage(Chatbox.Text, kontakt.GroupId);

                    Chatbox.Text = "";
                    
                    if (Chatbox.Text.Equals(""))
                    {
                        Chatbox.Text = "Nachricht schreiben";
                        Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
                        isChatBoxOnFocus = false;
                    }
                }
            }
            else
            {
                if (AktChatUserList.Items.IsEmpty)
                {
                    MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK);
                    if (Chatbox.Text.Equals(""))
                    {
                        Chatbox.Text = "Nachricht schreiben";
                        Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
                        isChatBoxOnFocus = false;
                    }
                }
                else if (Chatbox.Text.Equals(""))
                {
                    MessageBox.Show("Sie können keine lehre Nachricht verschicken.", "Fehler", MessageBoxButton.OK);
                    if (Chatbox.Text.Equals(""))
                    {
                        Chatbox.Text = "Nachricht schreiben";
                        Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
                        isChatBoxOnFocus = false;
                    }
                }
            }
        }

        private void Chatbox_OnGotFocus(object sender, RoutedEventArgs e)
        {
            if (Chatbox.Text.Equals("Nachricht schreiben"))
            {
                Chatbox.Text = "";
                Chatbox.Foreground = new SolidColorBrush(Colors.Black);
                isChatBoxOnFocus = true;
            }

            //hier bereich wie Dokumentieren 
        }

        private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Return)
                {
                    if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals(""))
                    {
                        var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];
 
                        _chat.AddeNachrichtDerView(Chatbox.Text);
                        
                        CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();
                        ChatListBox.Items.MoveCurrentToLast();
                        ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);
                       
                        _chat.SendMessage(Chatbox.Text, kontakt.GroupId);

              
                        Chatbox.Text = "";
                        
                    }
                    else
                    {
                        if (AktChatUserList.Items.IsEmpty)
                        {
                            MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK);
                        }
                        else if (Chatbox.Text.Equals(""))
                        {
                            MessageBox.Show("Sie können keine lehre Nachricht verschicken.", "Fehler", MessageBoxButton.OK);
                        }
                    }
                }
            }
            catch (Exception ed)
            {
                MessageBox.Show("Beim Senden einer Nachricht ist ein Fehler aufgetreten. " + ed.Message + "\n" + ed.StackTrace, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion

        #region Add Emoji To ChatBox
        public delegate void EmojiiDelegate(Button x);

        public event EmojiiDelegate OnEmojii;

        private void EmojiButton_OnClick(object sender, RoutedEventArgs e)
        {          
                //hier wie bei login 
                if (OnEmojii != null)
                {
                    OnEmojii(EmojiButton);
                }             
        }
        #endregion

        #region Nachladen weiterer Chat Nachrichten
        private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(ChatListBox);
            foreach (ScrollBar scrollBar in scrollBarList)
            {
                if (scrollBar.Orientation == Orientation.Horizontal)
                {
                    scrollBar.ValueChanged += HorizontalScrollbarChanged;
                    scrollPrueferAktivieren = true;
                }
                else
                {
                    scrollBar.ValueChanged += VerticalScrollbarChanged;
                }
            }
        }

        private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs<double> routedPropertyChangedEventArgs)
        {
            if (scrollPrueferAktivieren == true)
            {
                var x = (ScrollBar) sender;

                if (x.Value > 0)
                {
                    //nix
                }
                else
                {
                    Cursor = Cursors.Wait;
                    //StartWaiting();               
                    scrollPrueferAktivieren = false;

                    ChatListBox.Items.MoveCurrentToFirst();
                    ChatMessage item = ChatListBox.Items.CurrentItem as ChatMessage;

                    ChatListBox.ItemsSource = null;

                    var kontakt = (KontaktlistBuilder)Clientlist.SelectedItem;

                    var xy = _chat.LadeWeiterNachrichten(kontakt);

                    ChatListBox.ItemsSource = xy;

                    ChatListBox.ScrollIntoView(item);      
                    //EndWaiting();
                    Cursor = Cursors.Arrow;
                }           
            }         
        }

        private void HorizontalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs<double> routedPropertyChangedEventArgs)
        {
            //nix 

        }

        #region Get Scollbar von listbox
        private static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
        {
            List<T> visualCollection = new List<T>();
            GetVisualChildCollection(parent as DependencyObject, visualCollection);
            return visualCollection;
        }

        private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {
                    visualCollection.Add(child as T);
                }
                else if (child != null)
                {
                    GetVisualChildCollection(child, visualCollection);
                }
            }
        }

        #endregion

        #endregion
        
        #region Funktion Nachrichten Listener

        private void HorcheAktivNachNachrichten()
        {
            if (newThread != null)
            {
                newThread.Join();
                newThread = null;
            }
            
            var kontakt = (AktuellerKontakt)AktChatUserList.Items[0];

            //thred besser verwalten 
            newThread = new Thread(DoWork);
            newThread.IsBackground = true;
            newThread.Start(kontakt);
            
        }

        private void DoWork(object o)
        {
            bool _schaueNachMs = false;

            var kontakt = (AktuellerKontakt) o;
            while (true)
            {
                Thread.Sleep(2000);

                if (!disableKontaktNachrichtenThread)
                {
                    _schaueNachMs = _chat.SchaueNachNeuenNachrichten(kontakt);

                    if (_schaueNachMs == true)
                    {

                        this.Dispatcher.BeginInvoke(
                            DispatcherPriority.Background,
                            (Action) delegate
                            {
                                if (kontakt != null)
                                {

                                    var x = _chat.LadeChatNachrichtenVomKontakt(kontakt);

                                    CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh();

                                    ChatListBox.Items.MoveCurrentToLast();
                                    ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem);

                                }
                            });

                    }
                }
                else
                {
                    break;
                }
                
            }

        }

        #endregion

        #region Für alle Nachrichten Count Listener
        private void HorcheAlleGruppenNachrichten()
        {
            AlleKontakteThread = new Thread(DoWorkAlleNachrichten);
            AlleKontakteThread.IsBackground = true;
            AlleKontakteThread.Start();
        }
        
        private void DoWorkAlleNachrichten()
        {
            while (true)
            {               
                var x = _chat.SchaueNachAllenMessageCounts();  

                if (x > 0)
                {                                    
                    this.Dispatcher.BeginInvoke(
                    DispatcherPriority.Background,
                    (Action)delegate
                    {   
                        var alist = _chat.NeueGroupklassenKontakte();

                        AktuellerKontakt aktuellerKontakt = null;

                        if (AktChatUserList.HasItems)
                        {
                            aktuellerKontakt = (AktuellerKontakt)AktChatUserList.Items[0];
                        }

                        foreach (var liste in _kontaktlist)
                            {
                                foreach (var neu in alist)
                                {
                                    if (liste.GroupId == neu.GroupId)
                                    {
                                        if (!liste.ReceiveMs.Equals(neu.ReceiveMs)) {
                                        
                                            liste.ReceiveMs = neu.ReceiveMs;
                                            liste.TimeStamp = neu.TimeStamp;
                                        
                                            if (aktuellerKontakt != null && neu.GroupId == aktuellerKontakt.GroupId)
                                            {
                                                liste.SetzeGelesen = 0;
                                            }
                                            else
                                            {
                                                liste.SetzeGelesen = 1;
                                            }
                                        }
                                    }
                                    
                                    //abchecken ob neue Groupid in liste vorhanden , wenn nicht dann adde neuen kontakt der liste hinzu
                                    if (!_kontaktlist.Contains(neu))
                                    {
                                        _kontaktlist.ToList().Add(neu);
                                    }
                                }  
                                
                                //umgekert ist eine kontakt aus der liste nicht mehr in neu muss diese raus 
                                if (!alist.Contains(liste))
                                {
                                    _kontaktlist.ToList().Remove(liste);
                                }
                            }
                            

                        Clientlist.Items.Refresh();
                       
                    });
  
                }
                
                if (AlleNachrichtenThreadBool == false)
                {
                    break;
                }          
               
                Thread.Sleep(5000);        
            }
        }

        #endregion

        #region Suche Nach Person 
        
        private void Suche_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            CollectionViewSource.GetDefaultView(Clientlist.ItemsSource).Refresh();
        }

        private bool UserFilter(object item)
        {
            if (String.IsNullOrEmpty(Suche.Text))
                return true;
            else
                return ((item as KontaktlistBuilder).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0);
        }

        #endregion

        #region Zeige Erhaltene Daten per doppelclick An 

        private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Cursor = Cursors.Wait;
            
            var chatItems = ChatListBox.SelectedItems;

            if (chatItems.Count > 0)
            {
                foreach (var items in chatItems)
                {
                    var item = items as ChatMessage;

                    if (item != null && item.ImageSources != null)
                    {                       
                        StartWaiting();
                        _chat.ShowPicture(item, EndWaiting);                                             
                    }
                    else if(item != null && item.Dokpfad != null)
                    {
                        var filename = Path.GetFileName(item.Dokpfad.ToString());
                        LoadDokument(item.Dokpfad.ToString(), filename);
                    }                   
                }

                Cursor = Cursors.Arrow;
            }
            else
            {
                Cursor = Cursors.Arrow;
            }        
        }

        #endregion

        #region Lade Dokument Herunter und Zeige es an 
        private void OpenDokument_OnClick(object sender, RoutedEventArgs e)
        {
            OpenDocument(sender);
        }

        private void OpenDocument(object sender)
        {
            Cursor = Cursors.Wait;

            var btn = sender as System.Windows.Controls.Button;

            if (btn.Tag != null)
            {
                var link = btn.Tag;

                var filename = Path.GetFileName(link.ToString());

                LoadDokument(link.ToString(), filename);
            }

            Cursor = Cursors.Arrow;
        }

        private void LoadDokument(string link, String filename)
        {
            try
            {
                StartWaiting();

                string path = Path.Combine(Path.GetTempPath(), filename);
                createdTempFiles.Add(path);
                if (!File.Exists(path))
                {
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(link, path);
                    }

                    if (File.Exists(path))
                    {
                        Process.Start(path);
                    }
                }
                else
                {
                    Process.Start(path);
                }
            }
            catch (Exception e)
            {

            }
            finally
            {
                EndWaiting();
            }
            

                      
        }

        #endregion

        #region Wait Layer

        private ChatControlWaitLayer _waitLayer = null;

        public void StartWaiting()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)StartWaitingImmediately);
        }

        public void StartWaitingImmediately()
        {
            if (_waitLayer == null)
            {
                _waitLayer = new ChatControlWaitLayer();
                //Grid.SetColumnSpan(_waitLayer, 3);
                Grid.SetRowSpan(_waitLayer, 3);
                GridRechts.Children.Add(_waitLayer);
                Panel.SetZIndex(_waitLayer, int.MaxValue);
                _waitLayer.RefreshChatUI();               
            }
        }

        public void EndWaiting()
        {
            Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                (Action)delegate
                {
                    if (_waitLayer != null)
                    {
                        GridRechts.Children.Remove(_waitLayer);
                        _waitLayer = null;
                    }
                });
        }

        #endregion

        #region link request
        private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.ToString());
        }
        #endregion

        #region ReloadGruppen (For Stand Alone version)
        private void ButtonReloadGruppen_OnClick(object sender, RoutedEventArgs e)
        {        
            DoSynchro();
        }
        
        private void DoSynchro()
        {
            try
            {
                Cursor = Cursors.Wait;

                SpeichereMessageInfoInDatei();

                var aktuelleGruppen = _chat.GruppenAktuallisieren();

                var x = _chat.GroupklassenAktuallisieren(aktuelleGruppen);

                _kontaktlist = x;
                
                LeseMessageInfoAusDatei();
                
                Clientlist.Items.Refresh();
                
                Cursor = Cursors.Arrow;
            }
            catch (Exception e)
            {
                MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion
        
        #region speichern sowie lesen der MessageSyncDatei / stylezwecke (OwnChat only)
        public void SpeichereMessageInfoInDatei()
        {
            List<KontaktlistBuilder> aa = new List<KontaktlistBuilder>();
            foreach (var kontakt in _kontaktlist)
            {
                if(kontakt.SetzeGelesen == 0 && !kontakt.ReceiveMs.Equals("")) { 
                    aa.Add(kontakt);
                }
            }

            if(aa.Count>0)
                _chat.SpeichereTimeStampsInDatei(aa);
        }
        
        public void LeseMessageInfoAusDatei()
        {
            List<KontaktlistBuilder> aa = new List<KontaktlistBuilder>();
            foreach (var kontakt in _kontaktlist)
            {
                aa.Add(kontakt);
            }

            var liste = _chat.PruefeTimeStampsBeiStart(aa);

            if(liste != null) { 
                foreach (var kon in _kontaktlist)
                {
                    foreach (var item in liste)
                    {
                        if (kon.GroupId == item.Key)
                        {
                            kon.SetzeGelesen = 0;
                        }
                    }    
                }
            }          
        }
        #endregion
        
        #region Speichern Und LEsen Der MesageSyncDatei (Bewoplaner only) 

        public List<KontaktlistBuilder> UebergebeMessageInfoDatenFuerDb()
        {
            List < KontaktlistBuilder > aa = new List<KontaktlistBuilder>();

            Clientlist.Items.Refresh();

            foreach (var item in Clientlist.Items)
            {
                var kontakt = item as KontaktlistBuilder;
                
                if (kontakt != null && kontakt.SetzeGelesen == 0 && !kontakt.ReceiveMs.Equals(""))
                {
                    aa.Add(kontakt);
                }
            }
            
            return aa;
        }

        public void ErhalteMessageInfoVonDb(Dictionary<long,DateTime> liste)
        {
            if (liste != null)
            {
                foreach (var kon in _kontaktlist)
                {
                    foreach (var item in liste)
                    {
                        if (kon.GroupId == item.Key)
                        {
                            kon.SetzeGelesen = 0;
                        }
                    }
                }
            }      
        }
        
        #endregion

        public void DeleteTempFiles()
        {
            foreach (var file in createdTempFiles)
            {
                try
                {
                    if (File.Exists(file))
                        File.Delete(file);
                }
                catch (Exception e)
                {
                    //ignore
                }
            }
        }
    }
}
