using ChatController.ChatKlassen;
using ChatController.Klassen;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Application = System.Windows.Forms.Application;
using Clipboard = System.Windows.Forms.Clipboard;
using Color = System.Drawing.Color;
using ContextMenu = System.Windows.Controls.ContextMenu;
using DataFormats = System.Windows.Forms.DataFormats;
using Image = System.Windows.Controls.Image;
using MessageBox = System.Windows.MessageBox;
using Size = System.Drawing.Size;

namespace ChatController.HauptKlassen
{
    public class Chat
    {
        private readonly List<KontaktlistBuilder> Kontaktliste = new List<KontaktlistBuilder>();
        private readonly List<ChatMessage> Messages = new List<ChatMessage>();

        public ChatDatenUebergabe ChatDaten;

        private UserMessages _userMessages;
        private UserMessages _weitereUserMessages;

        private string _nextPage = null;
        private bool _hasNextPage = false;

        public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG" };
        public static readonly List<string> DokumentExtension = new List<string> { ".TXT", ".PPT", ".XLS", ".DOC",".PDF" };

        private long lastTimeStamp=0;
        
        public Chat(ChatDatenUebergabe chatDaten)
        {
            ChatDaten = chatDaten;
        }

        #region Gruppen In Kontaktliste Wandler
        public IOrderedEnumerable<KontaktlistBuilder> GroupklassenInChatKontakteUmwandler()
        {
            foreach (var kontakt in ChatDaten.AlleGruppen.Response)
            {
                foreach (var value in kontakt.Value)
                {
                    string message = "";
                    DateTime timestamp = new DateTime();

                    var lastMS = value.LastMessage;

                    DateTime timeformated = new DateTime();


                    if (lastMS != null)
                    {
                        if (lastMS.Text != null)
                        {
                            message = lastMS.Text;

                          
                        }
                    }

                    if( value.LastMessage != null) { 
                        timestamp = DateTime.Parse(lastMS.Timestamp.Date);

                        var clientZone = TimeZoneInfo.Local;
                        timeformated = TimeZoneInfo.ConvertTimeFromUtc(timestamp, clientZone);
                    }


                    if (message.Equals("") && value.LastMessage  != null && !value.LastMessage.File.Equals(""))
                    {
                        message = Path.GetFileName(value.LastMessage.File);
                    }

                    long? customerOid = null;
                    bool isC = false;
                    bool isE = false;
                    foreach (var user in value.Users)
                    {
                        //oid des 
                        if (user.Oid != ChatDaten.Userid)
                        {
                            if (!user.Is_Employee && !String.IsNullOrEmpty(user.Userid_Manage))
                            {

                                customerOid = Int64.Parse(user.Userid_Manage.Substring(1));
                                isC = true;
                            }
                        }
                    }

                    if (value.Onlyemployees && value.Users.Length == 2)
                    {
                        isE = true;
                    }

                    //null steht für employee
                    Kontaktliste.Add(new KontaktlistBuilder(value.Name, AvatarToImageSourceConverter(value.Avatar,isE,isC),
                        message, timeformated, value.Oid, customerOid, value.Onlyemployees,value.Users.Length));

                    if(lastMS != null && lastMS.Timestamp != null && lastMS.Timestamp.Date != null) { 
                        TimeSpan span = (DateTime.Parse(lastMS.Timestamp.Date) - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
                        long unixTime = System.Convert.ToInt64(span.TotalSeconds);

                        if (lastTimeStamp < unixTime)
                        {
                            lastTimeStamp = unixTime;
                        }
                    }
                }
            }

            var sortedKontaktliste = Kontaktliste.OrderByDescending(r => r.TimeStamp);

            return sortedKontaktliste;
            //Search Bereich 
            //CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
            //view.SortDescriptions.Add(new SortDescription("TimeStamp", ListSortDirection.Descending));
            //// view.SortDescriptions.Add(new SortDescription("StatusType", ListSortDirection.Descending));
            //view.Filter = UserFilter;
        }
        
        private ImageSource AvatarToImageSourceConverter(string avatar,bool isEmployee, bool isCustomer)
        {
            if (!avatar.Equals(""))
            {
                try
                {
                    Bitmap bitmap;
                    var request = WebRequest.Create(avatar);
                    using (var response = request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        bitmap = new Bitmap(stream);
                    }

                    MemoryStream ms = new MemoryStream();
                    bitmap.Save(ms, ImageFormat.Png);
                    ms.Position = 0;
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.StreamSource = ms;
                    bi.EndInit();
                    ms.Dispose();
                    ms.Close();

                    return bi;
                }
                catch (Exception e)
                {
                    return null;
                }
            }
            else
            {
                //team default png
                string defImage = "pack://application:,,,/ChatController;component/Ressourcen/team_default.png";

                if (isEmployee == true)//original true
                {
                    //employee default png
                    defImage = "pack://application:,,,/ChatController;component/Ressourcen/employee_default.png";
                }

                if (isCustomer == true)
                {
                    //client default png 
                    defImage = "pack://application:,,,/ChatController;component/Ressourcen/client_default.png";
                }
                
                try
                {
                    BitmapImage bix = new BitmapImage();
                    bix.BeginInit();
                    bix.UriSource = new Uri (defImage);//"pack://application:,,,/ChatController;component/Ressourcen/mitarbeiter-avatar.png" 
                    bix.EndInit();
                    return bix;
                }
                catch (Exception e)
                {
                    return null;
                }
            }
        }
        #endregion
    
        #region Lade Nachrichten vom Kontakt in den Chat
        public IOrderedEnumerable<ChatMessage> LadeChatNachrichtenVomKontakt(AktuellerKontakt kontakt)
        {
            if (kontakt != null)
            {
                HoleNachrichtenVomServer(kontakt.GroupId);
                Messages.Clear();

                foreach (var ChatMessage in _userMessages.Response.Messages)
                {
                    if (ChatMessage.UserId == ChatDaten.Userid.Value)
                    {
                        //var timeformated = DateTime.Parse(ChatMessage2.Timestamp.Date);

                        var time = DateTime.Parse(ChatMessage.Timestamp.Date);
                        var clientZone = TimeZoneInfo.Local;
                        var timeformated = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone);


                        if (!ChatMessage.File.Equals("")) 
                        {
                            string textn = "";

                            if (ChatMessage.Text != null)
                                textn = ChatMessage.Text;

                            if (textn.Equals(""))
                                textn = ChatMessage.Original_Filename;

                            if (ImageExtensions.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                            {
                                //string textn = "";

                                //if (ChatMessage2.Text != null)
                                //    textn = ChatMessage2.Text;

                                //if (textn.Equals(""))
                                //    textn = ChatMessage2.Original_Filename;

                                Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,
                                timeformated, true, LadeBildNach(ChatMessage.Smaller_Image),
                                ChatMessage.File, ChatMessage.Original_Filename));
                            }
                            else
                                if (DokumentExtension.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                                {
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,
                                    timeformated, true,ChatMessage.File));
                                }
                                else
                                { 
                                    //MP4 und gifs und so unbehandelten dreck 
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,
                                    timeformated, true,ChatMessage.File));
                                }
                        }
                        else
                        {
                            Messages.Add(new ChatMessage(ChatMessage.User_Name, ChatMessage.Text,
                                timeformated, true)); //dd MMMM yyyy HH:mm:ss
                        }
                    }
                    else
                    {
                        //var timeformated = DateTime.Parse(ChatMessage2.Timestamp.Date);

                        var time = DateTime.Parse(ChatMessage.Timestamp.Date);
                        var clientZone = TimeZoneInfo.Local;
                        var timeformated = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone);

                        if (!ChatMessage.File.Equals("")) 
                        {
                            string textn = "";

                            if (ChatMessage.Text != null)
                                textn = ChatMessage.Text;

                            if (textn.Equals(""))
                                textn = ChatMessage.Original_Filename;
                            
                            if (ImageExtensions.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                            {
                               
                                Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,
                                timeformated, false, LadeBildNach(ChatMessage.Smaller_Image),
                                ChatMessage.File, ChatMessage.Original_Filename));
                            }
                            else 
                                if (DokumentExtension.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                                {
                                    //Dokument
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name,textn,                                   
                                    timeformated, false, ChatMessage.File));
                                }
                                else
                                {
                                    //ALLERLEI UNBEHANDELTER KRAM 
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name,
                                    textn,
                                    timeformated, false, ChatMessage.File));
                                }
                        }
                        else
                        {
                            //Message
                            Messages.Add(new ChatMessage(ChatMessage.User_Name, ChatMessage.Text,
                                timeformated, false));
                        }
                    }
                }


                var x = Messages.OrderBy(r => r.SendTime);

                return x;
            }
            else
            {
                return Messages.OrderBy(r => r.SendTime);
            }
        }

        private ImageSource LadeBildNach(string link)
        {
            try
            {
                BitmapImage bix = new BitmapImage();
                bix.BeginInit();
                bix.UriSource = new Uri(link);
                bix.CacheOption = BitmapCacheOption.OnDemand;
                bix.EndInit();
                
                return bix;
            }
            catch (Exception edf)
            {
                return null;
            }
        }

        private void HoleNachrichtenVomServer(long groupId)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/chat/messages?groupid=" + groupId;

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;
               
                // Get the response.
                using (WebResponse response = request.GetResponse())
                {
                    // Display the status.
                    var statusResponse = ((HttpWebResponse) response).StatusDescription;


                    string responseFromServer = ReadStream(response);

                    //verarbeite hier zu json
                    if (!responseFromServer.Equals(""))
                    {
                        _userMessages = null;
                        //################# Deserialisierung mit Json ###############################
                        var jsonDaten = JsonConvert.DeserializeObject<UserMessages>(responseFromServer);

                        _userMessages = jsonDaten;

                        if (_userMessages.Response.HasMorePages == true)
                        {
                            _nextPage = _userMessages.Response.NextPage;
                            _hasNextPage = true;
                        }
                        else
                        {
                            _hasNextPage = false;
                        }
                    }
                    else
                    {
                        //   MessageBox.Show("Keine Daten Vorhanden.");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK);
            }

        }

        private string ReadStream(WebResponse response)
        {
            try
            {
                Stream dataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(dataStream);

                string responseFromServer = reader.ReadToEnd();


                dataStream.Dispose();
                reader.Dispose();

                dataStream.Close();
                reader.Close();

                return responseFromServer;
            }
            catch (Exception e)
            {
              //  MessageBox.Show(e.Message);
                return null;
            }
        }
        
        #endregion
        
        #region Lade Weiter Nachrichten

        public IOrderedEnumerable<ChatMessage> LadeWeiterNachrichten(KontaktlistBuilder kontakt)
        {
            if (_hasNextPage == true)
            {              
                HoleWeitereNachrichtenVomServer(kontakt.GroupId, _nextPage); 
            
                foreach (var ChatMessage in _weitereUserMessages.Response.Messages)
                {
                    if (ChatMessage.UserId == ChatDaten.Userid.Value)
                    {
                        //var timeformated = DateTime.Parse(ChatMessage2.Timestamp.Date);

                        var time = DateTime.Parse(ChatMessage.Timestamp.Date);
                        var clientZone = TimeZoneInfo.Local;
                        var timeformated = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone);


                        if (!ChatMessage.File.Equals("")) // Bilder werden Sichtbar 
                        {
                            string textn = "";

                            if (ChatMessage.Text != null)
                                textn = ChatMessage.Text;

                            if (textn.Equals(""))
                                textn = ChatMessage.Original_Filename;


                            if (ImageExtensions.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                            {
                                Messages.Add(new ChatMessage(ChatMessage.User_Name,textn,
                                timeformated, true, LadeBildNach(ChatMessage.Smaller_Image),
                                ChatMessage.File,ChatMessage.Original_Filename));
                            }
                            else 
                                if (DokumentExtension.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                                {
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name,textn,                                       
                                        timeformated, true, ChatMessage.File));
                                }
                                else
                                {
                                    // Der Ganze Unbehndelte Kram 
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name,textn,                                   
                                    timeformated, true, ChatMessage.File));
                                }
                        }
                        else
                        {
                            Messages.Add(new ChatMessage(ChatMessage.User_Name, ChatMessage.Text,
                                    timeformated, true));
                        }
                    }
                    else
                    {
                        //var timeformated = DateTime.Parse(ChatMessage2.Timestamp.Date);

                        var time = DateTime.Parse(ChatMessage.Timestamp.Date);
                        var clientZone = TimeZoneInfo.Local;
                        var timeformated = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone);

                        if (!ChatMessage.File.Equals("")) 
                        {
                            //image
                            string textn = "";

                            if (ChatMessage.Text != null)
                                textn = ChatMessage.Text;

                            if (textn.Equals(""))
                                textn = ChatMessage.Original_Filename;

                            if (ImageExtensions.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                            {
                                Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,
                                timeformated, false, LadeBildNach(ChatMessage.Smaller_Image),
                                ChatMessage.File,ChatMessage.Original_Filename));
                            }
                            else 
                                if (DokumentExtension.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()))
                                {
                                    //Dokument
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name, textn,                                  
                                    timeformated, false, ChatMessage.File));
                                }
                                else
                                {
                                    //Der Ganze Unbehandelte Kram MP4 und So 
                                    Messages.Add(new ChatMessage(ChatMessage.User_Name,textn,                                    
                                    timeformated, false, ChatMessage.File));
                                }                         
                        }
                        else
                        {
                            Messages.Add(new ChatMessage(ChatMessage.User_Name, ChatMessage.Text,
                                timeformated, false));
                        }
                    }
                }
            }


            var x = Messages.OrderBy(r => r.SendTime);

            return x;          
        }

        private void HoleWeitereNachrichtenVomServer(long groupId,string page)
        {
            try
            {
                var pa = page.Split('=');
                var endurl = ChatDaten.ServerUrl + "/api/chat/messages?groupid=" + groupId+"&page="+pa[1];

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;
                
                // Get the response.
                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;


                string responseFromServer = ReadStream(response);

                //verarbeite hier zu json
                if (!responseFromServer.Equals(""))
                {
                    _weitereUserMessages = null;
                    //################# Deserialisierung mit Json ###############################
                    var jsonDaten = JsonConvert.DeserializeObject<UserMessages>(responseFromServer);

                    _weitereUserMessages = jsonDaten;

                    if (_weitereUserMessages.Response.HasMorePages == true) //neu
                    {
                        _nextPage = _weitereUserMessages.Response.NextPage;
                        _hasNextPage = true;
                    }
                    else
                    {
                        _hasNextPage = false;
                    }

                }
                else
                {
                    //   MessageBox.Show("Keine Daten Vorhanden.");
                }

                response.Close();
            }
            catch (Exception e)
            {
                 MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion

        #region Prüfe ob Neue Nachrichten vorhanden sind 
        
        private double? _oldMessageCount;

        public bool SchaueNachNeuenNachrichten(AktuellerKontakt kontakt)
        {
            TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            long timespan = System.Convert.ToInt64(span.TotalSeconds);
            //long timespan = //lastTs.TotalSeconds;

            //Debug.Print(String.Format("Kontakt: {0}, Anzahl: {1}", kontakt.Name, _userMessages.Response.Messages.Length));
            if (_userMessages != null && _userMessages.Response.Messages.Length > 0)
            {
                timespan = _userMessages.Response.Messages.First().Created_At;
            }

            if (kontakt != null)
            {
                var newMsCount = SendOwnChatNewsRequest(kontakt.GroupId, timespan);

                if (_oldMessageCount == null)
                {
                    _oldMessageCount = newMsCount;
                }

                if (newMsCount.Value == _oldMessageCount.Value)
                {
                    return false;
                }
                else
                {
                    _oldMessageCount = newMsCount;
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        private double? SendOwnChatNewsRequest(long groupId, long lastStamp)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/ownchat/news/" + groupId+"/"+lastStamp;

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;
                
                // Get the response.
                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;
                
                
                string responseFromServer = ReadStream(response);
                
                var jsonDaten = JsonConvert.DeserializeObject<MessageCounter>(responseFromServer);

                return jsonDaten.MessageCount;

            }
            catch (Exception e)
            {
                return null;
            }
        }

        #endregion

        #region Prüfe für alle ob neue Nachrichten vorhanden sind 
        
        public double SchaueNachAllenMessageCounts()
        {   
            TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            long unixTime = System.Convert.ToInt64(span.TotalSeconds);

            var x = SendeTimestampForEach(0, unixTime);
            if (x > 0)
            {
                lastTimeStamp = unixTime;
            }
            return x;
        }

        private double SendeTimestampForEach(long groupId, long lastStamp)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/ownchat/news/" + groupId + "/" + lastTimeStamp; //lastStamp

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;
                ((HttpWebRequest) request).KeepAlive = false;

                // Get the response.
                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;


                string responseFromServer = ReadStream(response);

                var jsonDaten = JsonConvert.DeserializeObject<MessageCounter>(responseFromServer);

                return jsonDaten.MessageCount;

            }
            catch (Exception e)
            {
                return 0;
            }           
        }

        public IOrderedEnumerable<KontaktlistBuilder> NeueGroupklassenKontakte()
        {
            List<KontaktlistBuilder> Kontakt = new List<KontaktlistBuilder>();

            var daten = GruppenHolen();

            foreach (var kontakt in daten.Response)
            {
                foreach (var value in kontakt.Value)
                {
                    string message = "";
                    DateTime timestamp = new DateTime();
                    DateTime timeformated = new DateTime();

                    var lastMS = value.LastMessage;

                    if (lastMS != null)
                    {
                        if (lastMS.Text != null)
                        {
                            message = lastMS.Text;
                            timestamp = DateTime.Parse(lastMS.Timestamp.Date);

                            var clientZone = TimeZoneInfo.Local;
                            timeformated = TimeZoneInfo.ConvertTimeFromUtc(timestamp, clientZone);
                        }
                    }

                    if (message.Equals("") && value.LastMessage != null && !value.LastMessage.File.Equals(""))
                    {
                       message = Path.GetFileName(value.LastMessage.File);
                    }

                    long? customerOid = null;
                    bool isC = false;
                    bool isE = false;
                    foreach (var user in value.Users)
                    {
                        //oid des 
                        if (user.Oid != ChatDaten.Userid)
                        {
                            if (!user.Is_Employee && !String.IsNullOrEmpty(user.Userid_Manage))
                            {
                                customerOid = Int64.Parse(user.Userid_Manage.Substring(1));
                                isC = true;
                            }
                            
                        }
                    }

                    if (value.Onlyemployees && value.Users.Length == 2)
                    {
                        isE = true;
                    }
                    

                    //null steht für employee 
                    Kontakt.Add(new KontaktlistBuilder(value.Name, AvatarToImageSourceConverter(value.Avatar,isE,isC),
                        message, timeformated, value.Oid, customerOid, value.Onlyemployees, value.Users.Length));

                    if (lastMS != null && lastMS.Timestamp != null && lastMS.Timestamp.Date != null) { 
                        TimeSpan span = (DateTime.Parse(lastMS.Timestamp.Date) - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
                        long unixTime = System.Convert.ToInt64(span.TotalSeconds);

                        if (lastTimeStamp < unixTime)
                        {
                            lastTimeStamp = unixTime;
                        }
                    }

                }
            }


            var sortedKontaktliste = Kontakt.OrderByDescending(r => r.TimeStamp);

            return sortedKontaktliste;


            //Search Bereich 
            //CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
            //view.SortDescriptions.Add(new SortDescription("TimeStamp", ListSortDirection.Descending));
            //// view.SortDescriptions.Add(new SortDescription("StatusType", ListSortDirection.Descending));
            //view.Filter = UserFilter;
        }

        private ChatGruppenDaten GruppenHolen()
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/chat/groups";

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;

                // Get the response.
                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;


                string responseFromServer = ReadStream(response);

                //verarbeite hier zu json
                //################# Deserialisierung mit Json ###############################

                var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(responseFromServer);
                

                response.Close();
                

                return jsonDaten;
            }
            catch (Exception e)
            {
                 MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK);
                return null;
            }

        }
        #endregion

        #region Sende Normale Message an Kontakt
       
        public void AddeNachrichtDerView(string nachricht)
        {
            try
            {
                string username = "";

                foreach (var daten in ChatDaten.AngemeldeterUser.Response)
                {
                    username = daten.Value.Firstname + " " + daten.Value.Lastname;
                }

                var time = DateTime.Now;

                Messages.Add(new ChatMessage(username, nachricht,
                    time, true));
                         
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK);
            }            
        }
        
        public async void SendMessage(string message, long groupId)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/chat/messages/send";

                Dictionary<string, string> postparameter = new Dictionary<string, string>();

                postparameter.Add("groupid", groupId + "");
                postparameter.Add("text", message);
               
                using (MultipartFormDataContent multiPartContent = new MultipartFormDataContent())
                {
                    multiPartContent.Add(new StringContent(groupId + ""), "groupid");
                    multiPartContent.Add(new StringContent(message), "text");
                    
                    Uri requestUri = new Uri(endurl);

                    HttpRequestMessage httpRequest = new HttpRequestMessage();
                    httpRequest.Method = HttpMethod.Post;
                    httpRequest.RequestUri = requestUri;

                    //wegen Kontent nachschauen 
                    httpRequest.Content = multiPartContent;

                    httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
                    httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);


                    HttpResponseMessage httpResponse = null;

                    HttpClient httpClient = new HttpClient();
                    //httpClient.Timeout = TimeSpan.FromSeconds(300);
                    httpResponse = await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
                           
                    //string antwortResponse = await httpResponse.Content.ReadAsStringAsync();
                    
                }
               
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message,"Fehler",MessageBoxButton.OK);
            }
        }

        #endregion

        #region Sende Media Nachricht an Kontakt

        public string HoleMedium()
        {
            try
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();

                //if (typ == 1)
                openFileDialog1.Filter = "Office Dokumente |*.doc;*.xls;*.ppt;*.txt;*.pdf|Bilder |*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp";
                //else
                //    openFileDialog1.Filter = "Office Dokumente |*.doc;*.xls;*.ppt;*.txt"; 

                DialogResult result = openFileDialog1.ShowDialog();
                
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    return openFileDialog1.FileName;
                }
                else 
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
                return null;
            }
        }

        public void AddeMediumDerNachrichtView(string file,string originalFilePath)
        {
            try
            {
                var ChatMessage = _userMessages.Response.Messages.Last();

                var timeformated = DateTime.Now;

                if (ImageExtensions.Contains(Path.GetExtension(file).ToUpperInvariant()))
                {
                    byte[] mdatei;
                    using (Stream reader = File.OpenRead(file))
                    {
                        mdatei = ReadFully(reader);
                    }

                    MemoryStream mss = new MemoryStream(mdatei);
                    System.Drawing.Image Img = System.Drawing.Image.FromStream(mss);


                    using (System.Drawing.Bitmap dImg = new System.Drawing.Bitmap(Img))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            short orient = 0;
                            int orientationId = 0x0112;

                            if (Img.PropertyIdList.Contains(orientationId))
                            {
                                PropertyItem item = Img.GetPropertyItem(orientationId);


                                orient = BitConverter.ToInt16(item.Value, 0);
                                
                                dImg.SetPropertyItem(item);
                            }


                            var x = OrientationToFlipType(orient.ToString());

                            dImg.RotateFlip(x); 

                            dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);


                            System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();

                            bImg.BeginInit();
                            bImg.StreamSource = new MemoryStream(ms.ToArray());
                            bImg.EndInit();

                            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
                            img.Source = bImg;

                            //original image 
                            string filename = Path.GetFileName(originalFilePath).ToLower();
                            
                            filename = filename.Replace(".bmp", ".jpg");
                            
                            //Path.GetFileName(file)
                            Messages.Add(new ChatMessage(ChatMessage.User_Name, filename ,
                            timeformated, true, bImg,
                            file, filename));
                        }
                    }
                  
                    mss.Dispose();
                    mss.Close();
                }
                else if (DokumentExtension.Contains(Path.GetExtension(file).ToUpperInvariant()))
                {
                    Messages.Add(new ChatMessage(ChatMessage.User_Name, Path.GetFileName(file),
                    timeformated, true,file));
                }
                else
                {
                    //MP4 und gifs und so unbehandelten dreck 
                    Messages.Add(new ChatMessage(ChatMessage.User_Name, Path.GetFileName(file),
                    timeformated, true, file));
                }

            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        public void AddMediumContextDerNachrichtView(byte[] datei,string filename)
        {
            var ChatMessage = _userMessages.Response.Messages.Last();

            var timeformated = DateTime.Now;

            if (ImageExtensions.Contains(Path.GetExtension(filename).ToUpperInvariant()))
            {
                BitmapImage biImg = new BitmapImage();
                MemoryStream ms = new MemoryStream(datei);
                biImg.BeginInit();
                biImg.StreamSource = ms;
                biImg.EndInit();

                ms.Close();
                ImageSource logo = biImg;

                Messages.Add(new ChatMessage(ChatMessage.User_Name, Path.GetFileName(filename),
                timeformated, true, logo, filename, Path.GetFileName(filename)));
            }
            else 
            {
                Messages.Add(new ChatMessage(ChatMessage.User_Name, Path.GetFileName(filename),
                timeformated, true, filename));
            }
        }

        public void SendeMediumAnKontakt(AktuellerKontakt kontakt,string file,string originalFilePath)
        {
            try
            {             
                VerarbeiteMedia(file,kontakt,originalFilePath);   
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        private void VerarbeiteMedia(string file,AktuellerKontakt kontakt, string originalFilePath)
        {
            byte[] mdatei;
            using (Stream reader = File.OpenRead(file))
            {
                mdatei = ReadFully(reader);
            }
            
            string filename = Path.GetFileName(originalFilePath).ToLower();

            //Medium auflösung auf 80 % vom original setzen 
            //Image x = (Bitmap)((new ImageConverter()).ConvertFrom(mdatei));

            // image wieder in byte[] umwandeln und übergeben 
            if (ImageExtensions.Contains(Path.GetExtension(filename).ToUpperInvariant())){ 
                
                filename = filename.Replace(".bmp", ".jpg");

                SendMediaMessage(filename, kontakt.GroupId, mdatei);
            }
            else
            {
                SendMediaMessage(filename, kontakt.GroupId, mdatei);
            }

        }

        public string ScaleImage(string file,string format)
        {
            try
            {
                byte[] mdatei;
                using (Stream reader = File.OpenRead(file))
                {
                    mdatei = ReadFully(reader);
                }

             
                MemoryStream ms = new MemoryStream(mdatei);
                System.Drawing.Image Image = System.Drawing.Image.FromStream(ms);
                

                float width = 0;
                float height = 0;
                //Querformat
                if (Image.Height < Image.Width )
                {
                   
                    if (Image.Height > 1080)
                    {
                        float factor = (float)Image.Height / 1080;

                        height = 1080;

                        width = Image.Width / factor;
                    }
                    else
                    {
                        return file;
                    }
                }
                else if(Image.Height < 1080 && Image.Width < 1080 )
                {
                    return file;
                }
                else // Hochformat
                {
                    if (Image.Width > 1080)
                    {
                        float factor = (float)Image.Width / 1080;

                        width = 1080;

                        height = Image.Height / factor;
                    }
                    else
                    {
                        return file;
                    }
                }
                
                
                System.Drawing.Bitmap bmpScaled = new System.Drawing.Bitmap(Image,new Size((int)width,(int)height));

                int orientationId = 0x0112;
                
                if (Image.PropertyIdList.Contains(orientationId)) {
                    PropertyItem  item = Image.GetPropertyItem(orientationId);
                    
                    bmpScaled.SetPropertyItem(item);
                }

                using (Graphics gr = Graphics.FromImage(Image))
                {
                    gr.Clear(Color.Transparent);

                    // falls jemand mekert, muss die intergedönse erhöht werden  
                    gr.InterpolationMode = InterpolationMode.Low; // InterpolationMode.HighQualityBicubic;

                    
                    gr.DrawImage(bmpScaled, (int)width, (int)height);
                    //bitMap = gr.GetHdc();
                }

                ImageConverter converter = new ImageConverter();

                byte[] imageData = (byte[])converter.ConvertTo(bmpScaled, typeof(byte[]));

                
                string filePath =  System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + format;

               
                //".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG" 
                if (format.Equals(".JPG") || format.Equals(".JPE") || format.Equals(".JPEG") || format.Equals(".BMP"))
                {
                    bmpScaled.Save(filePath, ImageFormat.Jpeg);
                }else if (format.Equals(".PNG"))
                {
                    bmpScaled.Save(filePath, ImageFormat.Png);
                }
                else if (format.Equals(".GIF"))
                {
                    bmpScaled.Save(filePath, ImageFormat.Gif);
                }

                if (File.Exists(filePath))
                {
                    FileInfo f = new FileInfo(filePath);
                    long s1 = f.Length;

                    if (ChatDaten.MaxUploadSize < s1)
                    {
                        File.Delete(filePath);
                        return "";
                    }
                }
                else
                {
                    return "";
                }

                //byte[] datei;
                //using (Stream reader = File.OpenRead(filePath))
                //{
                //    datei = ReadFully(reader);
                //}
                ms.Dispose();
                ms.Close();
                
                return filePath;               
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message, "Fehler");
                return file;
            }
        }

        public static RotateFlipType OrientationToFlipType(string orientation)
        {
            switch (int.Parse(orientation))
            {
                case 1:
                    return RotateFlipType.RotateNoneFlipNone;
                    break;
                case 2:
                    return RotateFlipType.RotateNoneFlipX;
                    break;
                case 3:
                    return RotateFlipType.Rotate180FlipNone;
                    break;
                case 4:
                    return RotateFlipType.Rotate180FlipX;
                    break;
                case 5:
                    return RotateFlipType.Rotate90FlipX;
                    break;
                case 6:
                    return RotateFlipType.Rotate90FlipNone;
                    break;
                case 7:
                    return RotateFlipType.Rotate270FlipX;
                    break;
                case 8:
                    return RotateFlipType.Rotate270FlipNone;
                    break;
                default:
                    return RotateFlipType.RotateNoneFlipNone;
            }
        }
        
        private static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    {
                        return ms.ToArray();
                    }

                    ms.Write(buffer, 0, read);
                }
            }
        }

        private HttpRequestMessage httpRequest;

        private async void SendMediaMessage(string message, long groupId, byte[] mediaDatei)
        {
            try
            {
                #region test Multiplatform
                using (MultipartFormDataContent multiPartContent = new MultipartFormDataContent())
                {
                    Uri requestUri = new Uri(ChatDaten.ServerUrl + "/api/chat/messages/send");

                    multiPartContent.Add(new ByteArrayContent(mediaDatei, 0, mediaDatei.Count()), "file", message);
                    multiPartContent.Add(new StringContent(groupId + ""), "groupid");

                    httpRequest = new HttpRequestMessage();
                    httpRequest.Method = HttpMethod.Post;
                    httpRequest.RequestUri = requestUri;
                    httpRequest.Content = multiPartContent;
                    
                    httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
                    httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);


                    HttpResponseMessage httpResponse = null;

                    HttpClient httpClient = new HttpClient();
                    //httpClient.Timeout = TimeSpan.FromSeconds(300);
                    httpResponse = await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);


                    string antwortResponse = await httpResponse.Content.ReadAsStringAsync();
                    
                    //MessageBox.Show(antwortResponse);
                }
                #endregion
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion

        #region Context Menue Für Chat inkl. Funktionen
        public ContextMenu ErstelleKontextMenue()
        {
            ContextMenu context = new ContextMenu();
            
            System.Windows.Controls.MenuItem item1 = new System.Windows.Controls.MenuItem(); // jeweils umbenenen Speichern unter
            System.Windows.Controls.MenuItem item2 = new System.Windows.Controls.MenuItem(); // Einfügen
            System.Windows.Controls.MenuItem item3 = new System.Windows.Controls.MenuItem(); // Kopieren 

            context.Items.Add(item1);
            context.Items.Add(item2);
            context.Items.Add(item3);


            item1.Header = "Speichern unter";
            item1.Visibility = Visibility.Visible;
            
            item2.Header = "Einfügen";
            item2.Visibility = Visibility.Visible;

            item3.Header = "Kopieren";
            item3.Visibility = Visibility.Visible;

            //Image icon = new Image();
            //icon.Source = new BitmapImage(new Uri(@"..\..\Ressource\ClipboardDisabled.png", UriKind.Relative));
            //icon.Height = 16;
            //icon.Width = 16;//(new Size(16, 16));
            //item1.Icon = icon;

            return context;
        }

        #region Speichere Chat Doku / Media aufm PC
        public void SpeichernUnterFunkion(ChatMessage item)
        {
            if (item.ImageSources != null)
            {
            
                SpeichernUnter(1, Path.GetFileName(item.OriginalImage),
                    DownloadMediaDatei(item.OriginalImage));
            }
        }

        private byte[] DownloadMediaDatei(string pfad)
        {
            try
            {
                byte[] pic = null;

                using (WebClient client = new WebClient())
                {
                    pic = client.DownloadData(pfad);
                }

                return pic;
            }
            catch (Exception e)
            {
                //throw new Exception(e.Message);
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
                return null;
            }
        }

        private void SpeichernUnter(int filterTyp, string dateiname, byte[] datensatz)
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                saveFileDialog1.FileName = Path.GetFileName(dateiname);

                if (filterTyp == 1) // Bilder 
                {
                    saveFileDialog1.Filter = "Bilder |*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp";
                    saveFileDialog1.Title = "Bild Speichern";
                    saveFileDialog1.ShowDialog();
                }

                if (filterTyp == 2) //Office 
                {
                    saveFileDialog1.Filter = "Office Dokumente |*.doc;*.xls;*.ppt;*.txt";
                    saveFileDialog1.Title = "Dokument Speichern";
                    saveFileDialog1.ShowDialog();
                }

                if (filterTyp == 3) // Audio
                {
                    saveFileDialog1.Filter = "Audio Datei|*.wav;*.mp3;*.wma;*.aac;*.ogg;";
                    saveFileDialog1.Title = "Audio Speichern";
                    saveFileDialog1.ShowDialog();
                }

                if (saveFileDialog1.FileName != "")
                {
                    FileStream fs = (FileStream)saveFileDialog1.OpenFile();

                    fs.Write(datensatz, 0, datensatz.Length);

                    fs.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: "+e.Message,"Fehler",MessageBoxButton.OK);
            }
        }

        #endregion

        #region Fuege Daten Bilder usw via DragAndDrop in den Chat 
        public void Einfuegen(long groupOid, ChatMainControl chatMainControl)
        {         
            var d = System.Windows.Forms.Clipboard.GetDataObject();

            if (d.GetDataPresent(DataFormats.FileDrop))
            {
                try
                {
                    string[] fileList = d.GetData(DataFormats.FileDrop) as string[];

                    string filename = "";

                    FileStream file = null;

                    if (fileList != null)
                    {
                        if (File.Exists(fileList[0]))
                        {
                            filename = Path.GetFileName(fileList[0]);
                            
                            byte[] myBinary = File.ReadAllBytes(fileList[0]);
                            
                            AddMediumContextDerNachrichtView(myBinary,filename);
                            
                            CollectionViewSource.GetDefaultView(chatMainControl.ChatListBox.ItemsSource).Refresh();

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


                            SendMediaMessage(filename, groupOid, myBinary);
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
                }
            }
            else   
                if (d.GetDataPresent(DataFormats.Text))
                {
                    string text = (string)d.GetData(DataFormats.StringFormat);
                     
                    AddeNachrichtDerView(text);
                
                    CollectionViewSource.GetDefaultView(chatMainControl.ChatListBox.ItemsSource).Refresh();

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

                    SendMessage(text, groupOid);     
                }
                else               
                    if (d.GetDataPresent(DataFormats.Bitmap))
                    {
                        Bitmap pic = (Bitmap)d.GetData(DataFormats.Bitmap);

                        var bildname = GeneriereZuffalsNamen() + ".jpg";

                        System.Drawing.Image img = pic;
                
                        AddMediumContextDerNachrichtView(ImageToByteArray(img),bildname);
                        
                        CollectionViewSource.GetDefaultView(chatMainControl.ChatListBox.ItemsSource).Refresh();

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

                        SendMediaMessage(bildname,groupOid, ImageToByteArray(img)); 
                    }
                    else
                    {
                        MessageBox.Show("Der Zwischen-Speicher kann nicht verarbeitet werden.", "Fehler", MessageBoxButton.OK);
                    }              
        }

        public static byte[] ImageToByteArray(System.Drawing.Image image)
        {
            try
            {
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Bmp);
                    return ms.ToArray();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
                return null;
            }
        }

        private string GeneriereZuffalsNamen()
        {
            int lenght = 6;
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                                    "abcdefghijklmnopqrstuvwxyz" +
                                    "0123456789";
            var random = new Random();
            String Code = new string(Enumerable.Repeat(chars, lenght)
            .Select(s => s[random.Next(s.Length)]).ToArray());

            return Code;
        }
        #endregion

        #region Kopierne der Dinger im Chat für Alle Bereiche

        public void Kopieren(object data, int typ)
        { 
            if (typ == 1) // Text
            {             
                Clipboard.SetData(DataFormats.Text, data);
            }

            if (typ == 2) // Bild
            {
                Clipboard.SetData(DataFormats.Bitmap, data);
            }

            if (typ == 3) //Dokument
            {
                Clipboard.SetData(DataFormats.FileDrop, data);
            }
        }
        
        #endregion

        #endregion

        #region Zeige Kontakt Bild 

        public void ShowKontaktPicture(AktuellerKontakt curItem )
        {
            try
            {
                using (Form form = new Form())
                {
                    Image imgg = new Image();

                    imgg.Source = curItem.Image;

                    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                    MemoryStream ms = new MemoryStream();
                    encoder.Frames.Add(BitmapFrame.Create((BitmapSource) imgg.Source));
                    encoder.Save(ms);
                    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

                    Bitmap imgbit = new Bitmap(img);

                    form.StartPosition = FormStartPosition.CenterScreen;
                    form.Size = imgbit.Size;
                    form.Height += 60;
                    form.MinimumSize = new Size(150,150);

                    var width = (int)Math.Round(System.Windows.SystemParameters.PrimaryScreenWidth / 1.25);
                    var height = (int)Math.Round(System.Windows.SystemParameters.PrimaryScreenWidth / 2);

                    
                    form.MaximumSize = new Size(width,height);
                    form.FormBorderStyle = FormBorderStyle.Sizable;

                    form.MaximizeBox = false; 

                    form.Text = "ownChat";
                    form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); 
                    
                    PictureBox pb = new PictureBox();
                    pb.Dock = DockStyle.Fill;
                    pb.Image = imgbit;

                    pb.SizeMode = PictureBoxSizeMode.CenterImage;

                    pb.MaximumSize = new Size(500,500);

                    form.Controls.Add(pb);
                    form.ShowDialog();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: "+e.Message,"Fehler",MessageBoxButton.OK);
            }
        }

        public void ShowPicture(ChatMessage curItem, Action downloadCompletedCallback)
        {
            try
            {
                
                var webClient = new WebClient();
                webClient.DownloadDataCompleted += (s, e) =>
                {
                    try
                    {

                        using (Form form = new Form())
                        {
                            using (var ms = new MemoryStream(e.Result))
                            {
                                System.Drawing.Image Img = System.Drawing.Image.FromStream(ms);


                                using (System.Drawing.Bitmap dImg = new System.Drawing.Bitmap(Img))
                                {
                                    using (MemoryStream mss = new MemoryStream())
                                    {
                                        short orient = 0;
                                        int orientationId = 0x0112;

                                        if (Img.PropertyIdList.Contains(orientationId))
                                        {
                                            PropertyItem item = Img.GetPropertyItem(orientationId);

                                            orient = BitConverter.ToInt16(item.Value, 0);

                                            dImg.SetPropertyItem(item);

                                        }


                                        var x = OrientationToFlipType(orient.ToString());

                                        dImg.RotateFlip(x);

                                        form.StartPosition = FormStartPosition.CenterScreen;
                                        form.ClientSize = dImg.Size;
                                        //form.MinimumSize = new Size(180, 180);
                                        form.FormBorderStyle = FormBorderStyle.Sizable;
                                        form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
                                        using (var pb = new PictureBox())
                                        {
                                            pb.Dock = DockStyle.Fill;
                                            pb.Image = dImg;

                                            pb.SizeMode = PictureBoxSizeMode.Zoom;

                                            form.Controls.Add(pb);

                                            downloadCompletedCallback?.Invoke();

                                            form.ShowDialog();

                                        }

                                        //form.Size = dImg.Size; //imgbit
                                        //form.MinimumSize = new Size(180, 180);

                                        //#region Screen Size-ing

                                        //int width = 0;
                                        //int height = 0;
                                        //int targetwidth =
                                        //    (int) Math.Round(System.Windows.SystemParameters.PrimaryScreenWidth / 1.25);


                                        ////Querformat
                                        //if (dImg.Height < dImg.Width)
                                        //{

                                        //    float factor = (float) dImg.Height / targetwidth;

                                        //    height = targetwidth;

                                        //    width = (int) Math.Round(dImg.Width / factor);

                                        //}
                                        //else // Hochformat
                                        //{
                                        //    float factor = (float) dImg.Width / targetwidth;

                                        //    width = targetwidth;

                                        //    height = (int) Math.Round(dImg.Height / factor);

                                        //}

                                        //if (dImg.Width < targetwidth)
                                        //{
                                        //    width = dImg.Width;
                                        //    height = dImg.Height;
                                        //}


                                        //int targetheight =
                                        //    (int) Math.Round(System.Windows.SystemParameters.PrimaryScreenHeight / 1.25);


                                        ////Querformat
                                        //if (dImg.Height < dImg.Width)
                                        //{

                                        //    float factor = (float) dImg.Width / targetheight;

                                        //    width = targetheight;

                                        //    height = (int) Math.Round(dImg.Height / factor);

                                        //}
                                        //else // Hochformat
                                        //{
                                        //    float factor = (float) dImg.Height / targetheight;

                                        //    height = targetheight;

                                        //    width = (int) Math.Round(dImg.Width / factor);

                                        //}

                                        //if (dImg.Height < targetheight)
                                        //{
                                        //    width = dImg.Width;
                                        //    height = dImg.Height;
                                        //}


                                        //if (width < 150 || height < 150)
                                        //{
                                        //    width = 150;
                                        //    height = 150;
                                        //}

                                        //#endregion

                                        //form.MaximumSize = new Size(width, height);


                                        //form.FormBorderStyle = FormBorderStyle.Sizable;

                                        //form.MaximizeBox = false;

                                        //form.Text = "ownChat";
                                        //form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);

                                        //PictureBox pb = new PictureBox();
                                        //pb.Dock = DockStyle.Fill;
                                        //pb.Image = dImg; //imgbit

                                        //pb.SizeMode = PictureBoxSizeMode.CenterImage;

                                        //form.Controls.Add(pb);
                                        //form.ShowDialog();
                                    }
                                }
                            }

                        }
                    }
                    catch (Exception edf)
                    {
                        MessageBox.Show("Fehler: " + edf.Message, "Fehler", MessageBoxButton.OK);
                    }
                    
                };
                webClient.DownloadDataAsync(new Uri(curItem.OriginalImage));
                
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
            }
        }

        #endregion
        
        #region Synchronisation Veranlassen für Bewoplaner OwnChat Version 
        //sync für alles und jeden
        //public bool DoSync = true;

        public bool DoSynchronisation( string apikey, string customerid)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/ownchat/sync/schedule/"+apikey+"/" +customerid; 

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Proxy = null;

                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;

                string responseFromServer = ReadStream(response);

                var definiti = new { result = "" };

                var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti);


                switch (jsonDatentyp.result)
                {
                    case "0":  /*MessageBox.Show("Syncanforderung wurde für fünf Minuten in der Zukunft hinterlegt.", "Info", MessageBoxButton.OK);*/ return true;// gebe grünes licht für Aktualieserung des Chattes / Bei Invalid access ChatMaincontroll Schließen  
                    break;
                    case "11": MessageBox.Show("Kundennummer unbekannt.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); return false; //rausschmeißen ?!
                    break;
                    case "12": MessageBox.Show("Der API-Key ist falsch -> Auth-Error.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); return false;//rausschmeißen ?!
                    break;
                    case "13": MessageBox.Show("Es existiert kein API-Key für die angegebene Kundennummer.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); return false;//rausschmeißen ?!
                    break;
                    case "x":  MessageBox.Show("MySQL Error.\nDer Chat wird jetzt geschlossen", "Fehler",MessageBoxButton.OK); return false;//rausschmeißen ?!
                    break;
                }

                return false;                   
            }
            catch (Exception e)
            {
                MessageBox.Show("Die verbindung konnte nicht aufgebaut werden.", "Fehler ", MessageBoxButton.OK);
                return false;
            }
        }

        #endregion

        #region Maximal erlaubte File Größe

        public long GetMaiximumAllowedFileUploadSize(string apikey,string customerid)
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/ownchat/uploadmaxsize";// + apikey + "/" + customerid;

                WebRequest request = WebRequest.Create(endurl);
                request.Headers["Token"] = apikey;
                request.Headers["CustomerID"] = customerid;

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Proxy = null;

                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;

                string responseFromServer = ReadStream(response);

                var definiti = new { file_upload_max_size = "" };

                var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti);


                return Convert.ToInt64(jsonDatentyp.file_upload_max_size);
            }
            catch (Exception e)
            {
                throw;
            }
        }


        #endregion

        #region Neue Gruppen Holen für OwnChatDesktop
        public ChatGruppenDaten GruppenAktuallisieren()
        {
            try
            {
                var endurl = ChatDaten.ServerUrl + "/api/chat/groups";

                WebRequest request = WebRequest.Create(endurl);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.Headers["Token"] = ChatDaten.AuthToken;
                request.Headers["CustomerID"] = ChatDaten.Kundennummer;

                // Get the response.
                WebResponse response = request.GetResponse();

                // Display the status.
                var statusResponse = ((HttpWebResponse)response).StatusDescription;


                string responseFromServer = ReadStream(response);


                response.Close();
                //verarbeite hier zu json
                if (!responseFromServer.Equals(""))
                {
                    //################# Deserialisierung mit Json ###############################
                    var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(responseFromServer);

                    //_groupconect = jsonDaten;
                    //// var serv = jsonDaten[_chatcode].ServerName;

                    ////MessageBox.Show(responseFromServer);
                    //_gruppeholenverbindungsaufbauOK = true;
                    
                    return jsonDaten;
                }
                return null;
            }
            catch (Exception e)
            {
                MessageBox.Show("Beim Aktualisieren der Kontaktliste ist ein Fehler aufgetreten.\nFehler:\n"+e.Message, "Fehler", MessageBoxButton.OK);
                return null;
            }
        }

        public IOrderedEnumerable<KontaktlistBuilder> GroupklassenAktuallisieren(ChatGruppenDaten chatDaten)
        {
            try
            {
                Kontaktliste.Clear();
                foreach (var kontakt in chatDaten.Response)
                {
                    
                    foreach (var value in kontakt.Value)
                    {
                        //var val = Kontaktliste.Find(item => item.GroupId == value.Oid);

                        //if (val == null) //was tun wenn der nicht merh drinne ist  ??  dann ist das ja auch null 
                        //{
                        string message = "";
                        DateTime timestamp = new DateTime();

                        var lastMS = value.LastMessage;


                        if (lastMS != null)
                        {
                            if (lastMS.Text != null)
                            {
                                message = lastMS.Text;
                                timestamp = DateTime.Parse(lastMS.Timestamp.Date);
                            }
                        }

                        if (message.Equals("") && value.LastMessage != null && !value.LastMessage.File.Equals(""))
                        {
                            message = Path.GetFileName(value.LastMessage.File);
                        }

                        long? customerOid = null;
                        bool isC = false;
                        bool isE = false;
                        foreach (var user in value.Users)
                        { 
                            if (user.Oid != ChatDaten.Userid && !String.IsNullOrEmpty(user.Userid_Manage))
                            {
                                if (!user.Is_Employee)
                                {
                                    customerOid = Int64.Parse(user.Userid_Manage.Substring(1));
                                    isC = true;
                                }
                            }
                        }

                        if (value.Onlyemployees && value.Users.Length == 2)
                        {
                            isE = true;
                        }
                        
                        Kontaktliste.Add(new KontaktlistBuilder(value.Name,
                                AvatarToImageSourceConverter(value.Avatar,isE,isC),
                                message, timestamp, value.Oid, customerOid, value.Onlyemployees, value.Users.Length));
                        //}
                        //else
                        //{
                        //    //Item Bereits vorhanden
                        //}
                    }
                }


                var sortedKontaktliste = Kontaktliste.OrderByDescending(r => r.TimeStamp);

                return sortedKontaktliste;
            }
            catch (Exception e)
            {
                MessageBox.Show("Bein sortieren der Aktualisierten Kontakte ist ein Fehler aufgetreten.\nFehler:\n",
                    "Fehler", MessageBoxButton.OK);
                return null;
            }

            //Search Bereich 
            //CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource);
            //view.SortDescriptions.Add(new SortDescription("TimeStamp", ListSortDirection.Descending));
            //// view.SortDescriptions.Add(new SortDescription("StatusType", ListSortDirection.Descending));
            //view.Filter = UserFilter;
        }
        #endregion

        #region pruefe letzten Konversations timestamp für design element 

        public Dictionary<int, DateTime> PruefeTimeStampsBeiStart(List<KontaktlistBuilder> kontaktliste)
        {
            try
            {
                if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt")))
                {
                    Dictionary<string,string> merkdaten = new Dictionary<string, string>(); 

                    using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), true))
                    {
                        string line = "";

                        while ((line = sr.ReadLine()) != null)
                        {
                            var encodedTextBytes = Convert.FromBase64String(line);

                            string plainText = Encoding.UTF8.GetString(encodedTextBytes);

                            var plainarray = plainText.Split(';'); 

                            merkdaten.Add(plainarray[0], plainarray[1]);
                        }
                    }

                    Dictionary<int, DateTime> rueckgabe = new Dictionary<int, DateTime>();

                    foreach (var kontakt in kontaktliste)
                    {
                        foreach (var daten in merkdaten)
                        {
                            var groupoid = Int32.Parse(daten.Key);

                            if (kontakt.GroupId == groupoid)
                            {
                                var datetime = DateTime.Parse(daten.Value);

                                if (kontakt.TimeStamp.Equals(datetime))
                                {
                                    rueckgabe.Add(groupoid,datetime);   
                                }   
                            }
                        }
                    }

                    if (rueckgabe.Count > 0)
                    {
                        return rueckgabe;
                    }
                    else
                    {
                        return null;
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public void SpeichereTimeStampsInDatei( List<KontaktlistBuilder> kontaktliste )
        {
            try
            {
                if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt")))
                {
                    using (
                        StreamWriter sw =
                            new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt")))
                    {

                        Encoding enc = new UTF8Encoding();

                        foreach (var kontakt in kontaktliste)
                        {
                            var text = kontakt.GroupId + ";" + kontakt.TimeStamp+";";
                            var byt = enc.GetBytes(text);
                            var bytes = Convert.ToBase64String(byt);

                            sw.WriteLine(bytes);
                        }
                        
                        File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"),
                            FileAttributes.ReadOnly);
                    }
                }
                else
                {
                    File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), FileAttributes.Normal);
                    File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"));

                    using (
                        StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt")))
                    {

                        Encoding enc = new UTF8Encoding();

                        foreach (var kontakt in kontaktliste)
                        {
                            var text = kontakt.GroupId + ";" + kontakt.TimeStamp + ";";
                            var byt = enc.GetBytes(text);
                            var bytes = Convert.ToBase64String(byt);

                            sw.WriteLine(bytes);
                        }

                        File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"),
                            FileAttributes.ReadOnly);
                    }
                }
            }
            catch (Exception e)
            {

            }
        }

        private static string GetAndCreateUserAppDataPath()
        {
            try
            {
                string localAppData = Environment.GetFolderPath(
                    Environment.SpecialFolder.LocalApplicationData);
                string companyFilePath
                    = Path.Combine(localAppData, "beyondSoft");

                if (!Directory.Exists(companyFilePath))
                    Directory.CreateDirectory(companyFilePath);

                string bewoFilePath
                    = Path.Combine(companyFilePath, "OwnChat");

                if (!Directory.Exists(bewoFilePath))
                    Directory.CreateDirectory(bewoFilePath);

                return bewoFilePath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" +
                    ex.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        }

        #endregion
    }
}
