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<KontaktMessageBuilder> _Orderedmessagelist;
        private IOrderedEnumerable<KontaktlistBuilder> _kontaktlist;

        private readonly List<KontaktMessageBuilder> _messagelist = new List<KontaktMessageBuilder>();

        private ChatDatenUebergabe _chatDaten;

        private bool scrollPrueferAktivieren = false;

        public Thread newThread;
        public bool threadBool = true;

        public Thread AlleKontakteThread;
        public bool AlleNachrichtenThreadBool = true;
        private double? AlleNachrichtenCount = null;


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

        public delegate void CloseDelegate();

        public event CloseDelegate OnClose;
        #endregion

        public ChatMainControl()
        {
            InitializeComponent();           
        }

        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();
        }
        
        public AktuellerKontakt GetAktuellenKontakt()
        {
            if (AktChatUser != null)
            {
                var kontakt = (AktuellerKontakt) AktChatUser.Items[0];

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

                return kontakt;
            }
            else
            {
                return null;
            }
        }

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

            foreach (Object selecteditem in Chat.SelectedItems)
            {
               KontaktMessageBuilder Item = selecteditem as KontaktMessageBuilder;

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

            if(itemListe.Count > 0) { 

                return itemListe;
            }
            else
            {
                return null;
            }
        }

        public void SetzteStyleAufNull()
        {
            EmojiButton.Style = null;
            MediaButton.Style = null;
            ReloadGruppen.Visibility = Visibility.Visible;
        }

        public void SynchronisationVeranlassen()
        {
            try
            {
                bool doSync = true;

                do
                {
                    doSync = _chat.DoSynchronisation(_chatDaten.ApiKey, _chatDaten.Kundennummer);

                    if (true || doSync)
                    {
                        var aktuelleGruppen = _chat.GruppenAktuallisieren();

                        var x = _chat.GroupklassenAktuallisieren(aktuelleGruppen);

                        _kontaktlist = x;

                        Dispatcher.BeginInvoke(
                            DispatcherPriority.Normal,
                            (Action) delegate
                            {
                                Clientlist.Items.Refresh();
                            });
                        //this.Dispatch(delegate // hä ?? 
                        //{
                        //    Clientlist.Items.Refresh();
                        //});

                        Thread.Sleep(TimeSpan.FromMinutes(5));
                    }

                } while (doSync);

                //sobald nicht mehr in der Schleife dann Close weil dann Sync false
                if (OnClose != null)
                {
                    OnClose();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler",MessageBoxButton.OK);
            }
        }

        #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();

                Cursor = Cursors.Wait;
                scrollPrueferAktivieren = false;
                Chat.ItemsSource = null;

                AktChatUser.Items.Clear();

                var kontakt = (KontaktlistBuilder)Clientlist.SelectedItem;

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

                    Clientlist.Items.Refresh();
                }

                var aktuellerKontakt = new AktuellerKontakt(kontakt);

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

                var x =  _chat.LadeChatNachrichtenVomKontakt(aktuellerKontakt);

                Chat.ItemsSource = x;

                Chat.Items.MoveCurrentToLast();
                Chat.ScrollIntoView(Chat.Items.CurrentItem);
            
                Chat.ContextMenu = _chat.ErstelleKontextMenue();
                SetContextHandler();
                scrollPrueferAktivieren = true;
            
                HorcheAktivNachNachrichten();
                Cursor = Cursors.Arrow;

                EndWaiting();
            }
        }
        
        #endregion

        #region Context Menue
        //ab Hier Kontext Menü
        private void SetContextHandler()
        {
            var contextItems = Chat.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 Chat.SelectedItems)
            {
                var item = (KontaktMessageBuilder)items;

                _chat.SpeichernUnterFunkion(item);
            }
        }

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

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

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

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

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

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

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


                }
            }
            else
            {
                //Schalte speichern unter Aus 
                var contextItems = Chat.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 = Chat.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else if (d.GetDataPresent(DataFormats.Text))
            {
                var contextItems = Chat.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else if (d.GetDataPresent(DataFormats.Bitmap))
            {
                var contextItems = Chat.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Visible;
            }
            else
            {
                var contextItems = Chat.ContextMenu.Items;
                var ContextItemSpeichernUnter = (MenuItem)contextItems[1];
                ContextItemSpeichernUnter.Visibility = Visibility.Collapsed;
            }

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


            if (Chat.ContextMenu.Items.Count == 0)
            {
                Chat.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 (AktChatUser.Items.Count > 0)
            {
                var kontakt = (AktuellerKontakt) AktChatUser.Items[0];

                _chat.HoleUndSendeMediumAnKontakt(kontakt);

                Chat.ItemsSource = null;
                Chat.ItemsSource = _chat.LadeChatNachrichtenVomKontakt(kontakt);

                Chat.Items.MoveCurrentToLast();
                Chat.ScrollIntoView(Chat.Items.CurrentItem);
            }
            else
            {
                MessageBox.Show("Bitte einen Kontakt auswählen!","Fehler",MessageBoxButton.OK);
            }
        }
        #endregion

        #region Sende Normale Nachrichten
        private void SendButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (!AktChatUser.Items.IsEmpty && !Chatbox.Text.Equals("") && isChatBoxOnFocus)
            {
                if (!Chatbox.Text.Equals(""))
                {
                    var kontakt = (AktuellerKontakt)AktChatUser.Items[0];

                    var text = Chatbox.Text;
                    
                    _chat.SendMessage(Chatbox.Text, kontakt.GroupId);


                    Chatbox.Text = "";

                    //Lade Nachrichten nach

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

                    if (Chatbox.Text.Equals(""))
                    {
                        Chatbox.Text = "Nachricht schreiben";
                        Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray);
                        isChatBoxOnFocus = false;
                    }
                }
            }
            else
            {
                if (AktChatUser.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 (!AktChatUser.Items.IsEmpty && !Chatbox.Text.Equals(""))
                    {
                        var kontakt = (AktuellerKontakt)AktChatUser.Items[0];

                        var text = Chatbox.Text;
                        
                        _chat.SendMessage(Chatbox.Text, kontakt.GroupId);

                        Chatbox.Text = "";


                        //lade Nachrichten nach 
                     
                    }
                    else
                    {
                        if (AktChatUser.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>(Chat);
            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;
                    
                    Chat.Items.MoveCurrentToFirst();
                    KontaktMessageBuilder item = Chat.Items.CurrentItem as KontaktMessageBuilder;
                   
                    Chat.ItemsSource = null;

                    var kontakt = (KontaktlistBuilder)Clientlist.SelectedItem;

                    var xy = _chat.LadeWeiterNachrichten(kontakt);

                    Chat.ItemsSource = xy;
                  
                    Chat.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()
        {
            threadBool = false;

            if (newThread != null)
            {
                newThread.Join();
                newThread = null;
            }
            
            var kontakt = (AktuellerKontakt)AktChatUser.Items[0];

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

        private void DoWork(object o)
        {
            threadBool = true;

            bool _schaueNachMs = false;

            var kontakt = (AktuellerKontakt) o;
            while (true)
            {
                _schaueNachMs = _chat.SchaueNachNeuenNachrichten(kontakt);

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

                            //neuer Aufruf villeicht nur von 
                            //Cursor = Cursors.Wait;

                            Chat.ItemsSource = null;

                            //Wichtig Verbessern
                            var x = _chat.LadeChatNachrichtenVomKontakt(kontakt);

                            //foreach (var liste in _Orderedmessagelist)
                            //{
                            //    foreach (var neu in alist)
                            //    {

                            //        if (liste.ChatMessageOid == neu.ChatMessageOid)
                            //        {
                            //            //_Orderedmessagelist.CreateOrderedEnumerable(neu,,true);

                            //            //if (!liste.ReceiveMs.Equals(neu.ReceiveMs))
                            //            //{
                            //            //    liste.ReceiveMs = neu.ReceiveMs;
                            //            //    liste.SetzeGelesen = 1;
                            //            //    //Vorher noch abfragen ob die id gleich den chat ist und dann nur wenn nicht zutrifft dann auf 1 setzen
                            //            //}
                            //        }
                            //    }
                            //}

                           
                            Chat.ItemsSource = x;
                                
                            //Cursor = Cursors.Arrow;

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

                        }
                    });
                     
                    _schaueNachMs = false;
                    
                }
             
                if (threadBool == false)
                {
                    break;
                }

                Task.Delay(2000);
                //Thread.Sleep(2000);
            }

        }

        #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 (AlleNachrichtenCount == null)
                {
                    AlleNachrichtenCount = x;
                }

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

                        var aktuellerKontakt =(AktuellerKontakt)AktChatUser.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;
                                        
                                        if (neu.GroupId == aktuellerKontakt.GroupId)
                                        {
                                            liste.SetzeGelesen = 0;
                                        }
                                        else
                                        {
                                            liste.SetzeGelesen = 1;
                                        }
                                    }
                                }
                            }
                        }

                        Clientlist.Items.Refresh();           
                    });

                    AlleNachrichtenCount = x;
                }
                
                if (AlleNachrichtenThreadBool == false)
                {
                    break;
                }

                Task.Delay(5000);
               
                //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 In Dem Fall Bilder Zurzeit

        private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var chatItems = Chat.SelectedItems;

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

                    if (item != null && item.ImageSources != null)
                    {
                       
                        _chat.ShowPicture(item);
                       
                    }
                }
            }
        }

        #endregion

        #region Lade Dokument Herunter und Zeige es an 
        private void OpenDokument_OnClick(object sender, RoutedEventArgs e)
        {
            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)
        {        
            string path = @"c:\temp\" + filename;

            if (!File.Exists(path))
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(link, path);
                }

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

        #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)
        {
            //Thread newThread = new Thread(DoSynchro);
            //newThread.IsBackground = true;
            //newThread.Start();          
            DoSynchro();
        }
        
        private void DoSynchro()
        {
            try
            {
                Cursor = Cursors.Wait;

                //StartWaiting();

                var doSync = _chat.DoSynchronisation(_chatDaten.ApiKey, _chatDaten.Kundennummer);

                if (doSync)
                {
                    var aktuelleGruppen = _chat.GruppenAktuallisieren();

                    var x = _chat.GroupklassenAktuallisieren(aktuelleGruppen);

                    _kontaktlist = x;

                    Clientlist.Items.Refresh();

                    Cursor = Cursors.Arrow;
                }
                else
                {
                    Cursor = Cursors.Arrow;
                    // EndWaiting();
                    if (OnClose != null)
                    {
                        OnClose();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion
    }
}
