using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
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.Navigation;
using System.Windows.Threading;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Controls;
using BeWo.View.Detail;
using BeWo.ViewModel;

using Blacklight.Wpf.Controls;

using BS.Shared;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using BS.Shared.RSS;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Editors.Helpers;
using System.Net.Sockets;
using System.Collections;
using System.Net;
using System.Text;

namespace BeWo.View
{
	/// <summary>
	///     Interaction logic for HomeView.xaml
	/// </summary>
	public partial class HomeDragPanelView : BeWoView
	{
		private List<TaskDC> _AllTasks;


        //################# Variablen der Serveranwendung ################# 
        protected Socket m_mainSocket;
        protected Socket[] m_workerSocket = new Socket[10];

        protected ArrayList m_workerSocketList = ArrayList.Synchronized(new ArrayList());

        protected AsyncCallback asyncWorkerCallBack;
        protected int clientCount = 0;

        protected ListBox Clientlist = new ListBox();
        protected TextBox ServerStats = new TextBox();
        protected TextBox chat = new TextBox();

	    protected MiniChatView pav;
	    protected ChatView chatpav;


        SocketPacket socketDaten;
	    String erhaltenerDS;
	    Dictionary<string, MiniChatView> pavlist = new Dictionary<string, MiniChatView>(); 
        //################################################################

		public HomeDragPanelView()
		{
			InitializeComponent();

			txtHeader.Text = String.Format("{0} {1}", BeWoApp.LoggedOnUser.Employee.FirstName, BeWoApp.LoggedOnUser.Employee.LastName);
			txtVersion.Text = BeWoApp.Version;

			txtLoginTime.Text = string.Empty;
			txtLastLoginTime.Text = string.Empty;

			//PreparePanels();
			InitPanels(null);
			
#if DEBUG
            txtChangePassword.Visibility = Visibility.Visible;
#else
			if (BeWoApp.Tenant == "demo" || !BeWoApp.LoggedOnUser.HasRight(UserRightType.AllowChangeOwnPassword))
			{
				txtChangePassword.Visibility = Visibility.Collapsed;
			}
#endif
			// FillInbox();
			// FillOutbox();
			Loaded += HomeDragPanelViewLoaded;


            //####################### ServerAnwendung ############################

            onConnectionStart();

            chatpav = new ChatView("Whats chat", chat.Text, m_workerSocketList);

            chatpav.Visibility = Visibility.Collapsed;
            //####################################################################
		}

		private void PreparePanels()
		{
			ServiceFacade.DoOperationsServiceAsyncNoWait(s => s.GetUiElements(UiElementType.StartPanel, BeWoApp.LoggedOnUser.Employee.EmployeeOid, null, null), InitPanelsCallback, null);
		}

		private void InitPanelsCallback(IList<UiElementDC> elements, object state)
		{
			this.Dispatcher.BeginInvoke(
				DispatcherPriority.Normal,
				(Action)delegate
				{
					InitPanels(elements);
				});
		}

		private void InitPanels(IList<UiElementDC> elements)
		{
			listboxExpiringSupportConcepts.Items.Clear();
			listboxConferenceDates.Items.Clear();
			listboxBirthdays.Items.Clear();
			listboxNews.Items.Clear();
			listboxTasks.Items.Clear();
			//ListboxInternalNews.Items.Clear();
			InternalNewsGrid.Children.Clear();


			//if (elements == null || elements.Count == 0)
			//{
			//	//
			//}
			//else
			//{
			//	foreach (var uiElementDc in elements)
			//	{
			//		var xamlElement = System.Windows.Markup.XamlReader.Parse(uiElementDc.Xaml);
			//		if (xamlElement is DragDockPanel)
			//		{
			//			panelHost.Children.Add(xamlElement as UIElement);
			//		}
			//	}

			//}

			ReorderPanels();
		}

		private void HomeDragPanelViewLoaded(object o, RoutedEventArgs e)
		{
			InitContent();
			//Warum klappt das bei Köln Ring nicht?=
			if (BeWoApp.LoggedOnUser == null || BeWoApp.LoggedOnUser.ResetPasswordInfos == null)
				return;
			if (!BeWoApp.LoggedOnUser.ResetPasswordInfos.Any(a => a.HasToChangePW)) return;

			var fenster = new PasswortAenderungsView {AbbrechenButton = {IsEnabled = false}};
			fenster.CommandBindings.Clear();
			
			fenster.ShowDialog();
		}

		public void SaveState()
		{
			var order = new List<DragDockPanel>();
			DragDockPanel panelWithMaxHeight = null;
			double maxHeight = 0;
			double normalHeight = 0;

			var result = new List<DependencyObject>();

			foreach (object item in panelHost.Children)
			{
				var p = item as DragDockPanel;

				if (order.Count == 0)
				{
					order.Add(p);
				}
				else
				{
					int newIndex = -1;
					int index = 0;

					Vector rect = VisualTreeHelper.GetOffset(p);
					foreach (DragDockPanel item2 in order)
					{
						string name1 = p.Name;
						string name2 = item2.Name;

						Vector rect2 = VisualTreeHelper.GetOffset(item2);
						if (rect.Y < rect2.Y)
						{
							newIndex = index;
							continue;
						}

						if (Equals(rect.Y, rect2.Y) && rect.X < rect2.X)
						{
							newIndex = index;
							continue;
						}

						index++;
					}

					if (newIndex < 0)
					{
						order.Add(p);
					}
					else
					{
						order.Insert(newIndex, p);
					}
				}

				if (p.Height > maxHeight)
				{
					maxHeight = p.ActualHeight;
					panelWithMaxHeight = p;
				}
				else
				{
					normalHeight = p.ActualHeight;
				}
			}

			if ((maxHeight - normalHeight) > 1 && panelWithMaxHeight != null)
			{
				BeWoApp.AppSettings.StartupPanelMaximized = panelWithMaxHeight.Name;
			}
			else
			{
				BeWoApp.AppSettings.StartupPanelMaximized = null;
			}

			List<string> panelOrder = order.Select(item => item.Name).ToList();

			BeWoApp.AppSettings.StartupPanelOrder = panelOrder;
		}

		private void ButtonOpenServiceRecordView_Click(object sender, RoutedEventArgs e)
		{
			var btn = sender as Button;
			if (btn != null)
			{
				var dc = btn.Tag as CompactSupportConceptDC;

				if (dc != null)
					BeWoApp.MainControl.NavigateToServiceRecordView(dc.SupportConceptOid);
			}
		}

		private void InitBewoNews()
		{
			try
			{
				if (BeWoApp.Tenant != "demo")
				{
					LoadFeed();

					//LoadFeed("http://www.heise.de/foto/rss/news-atom.xml");
				}
			}
			catch (Exception)
			{
			}
		}

		private void InitBirthdays()
		{
			DateTime endOfWeek = DateTime.Now.GetNext(DayOfWeek.Sunday).Date;
			endOfWeek = endOfWeek.AddDays(1).GetNext(DayOfWeek.Sunday).Date;
			ServiceFacade.DoAnalysisServiceAsync(s1 => s1.GetPersonsHavingBirthday(endOfWeek), ReloadBirthdays);
		}

		private void InitContent()
		{
			SetMaximizedPanel();

			InitLoginInfo();
			InitExpiredSupportConcepts();
			InitNextConferenceDates();
			InitBewoNews();
			InitBirthdays();
			InitTasks();
			rb_open.IsChecked = true;
			UpdateInternalNews();
		}

		private void InitExpiredSupportConcepts()
		{
			// DateTime endOfWeek = DateTime.Now.GetNext(DayOfWeek.Sunday).Date;
			// DateTime endOfWeek2 = endOfWeek.AddDays(8);
			DateTime dt = DateTime.Now.AddMonths(BeWoApp.AppSettings.HilfeplanAuslaufAuswahl);
			ServiceFacade.DoAnalysisServiceAsync(s1 => s1.GetExpiringSupportConcepts(BeWoApp.LoggedOnUser.Employee.EmployeeOid, dt), ReloadExpiringSupportConcepts);
		}

		private void UpdateInternalNews()
		{
			var showTeamNews = BeWoApp.AppSettings.ShowTeamNews;
			//ServiceFacade.DoEmployeeServiceAsync(s => s.GetPublishedNewsItems(), cb => this.Dispatch(delegate { listboxInternalNews.ItemsSource = cb.OrderByDescending(i => i.PublishDate).ToList(); }));
			ServiceFacade.DoEmployeeServiceAsync(s => s.GetPublishedNewsItemsForEmployee(BeWoApp.LoggedOnUser.Employee.EmployeeOid, showTeamNews), RefreshInternalNews);
		}

		private void RefreshInternalNews(List<NewsItemDC> news)
		{
			this.Dispatch(delegate
			{

				var team2News = new Dictionary<long, TeamNewsItemVM>();
				var allNews = new TeamNewsItemVM();
				allNews.Team = new CompactTeamDC();
				allNews.Team.Name = "Allgemein";
				allNews.AllowEdit = false;
				allNews.IsTitleVisible = true;

				foreach (var newsItemDc in news)
				{
					if (newsItemDc.Team != null)
					{
						newsItemDc.AllowEdit = true;
						newsItemDc.TitleString = String.Format("{0:dd.MM.yyyy}: {1}", newsItemDc.PublishDate, newsItemDc.Title);
						if (!team2News.ContainsKey(newsItemDc.Team.TeamOid))
						{
							team2News[newsItemDc.Team.TeamOid] = new TeamNewsItemVM();
							team2News[newsItemDc.Team.TeamOid].Team = newsItemDc.Team;
							team2News[newsItemDc.Team.TeamOid].AllowEdit = true;
							team2News[newsItemDc.Team.TeamOid].IsTitleVisible = true;
						}
						if (newsItemDc.NewsItemOid.HasValue)
						{
							team2News[newsItemDc.Team.TeamOid].NewsItems.Add(newsItemDc);
						}
					}
					else
					{
						newsItemDc.TitleString = newsItemDc.Title;
						allNews.NewsItems.Add(newsItemDc);
					}
				}
				
				var list = team2News.Values.OrderBy(i => i.Team.Name).ToList();
				
				if (list.Count == 0)
					allNews.IsTitleVisible = false;
				list.Add(allNews);

				InternalNewsGrid.Children.Clear();
				InternalNewsGrid.Children.Add(CreateInternalNewsControlList(list));
				//ListboxInternalNews.ItemsSource = list;

			});
		}

		private UIElement CreateInternalNewsControlList(List<TeamNewsItemVM> list)
		{
			StackPanel sp = new StackPanel();
			foreach (var teamNewsItemVm in list)
			{
				sp.Children.Add(CreateInternalNewsTeamControl(teamNewsItemVm));
			}
			return sp;
		}

		private UIElement CreateInternalNewsTeamControl(TeamNewsItemVM teamNewsItemVm)
		{
			var sp = new StackPanel();
			foreach (var newsItem in teamNewsItemVm.NewsItems)
			{
				sp.Children.Add(CreateInternalNewsControl(newsItem));
			}
			

			if (teamNewsItemVm.IsTitleVisible)
			{
				Expander ex = new Expander();

				ex.Style = (Style)FindResource("FlatLineExpander");
				ex.IsExpanded = true;
				ex.Margin = new Thickness(0, 5, 5, 5);

				Grid grid = new Grid();
				grid.ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(1, GridUnitType.Auto)});
				grid.ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)});
				TextBlock tb = new TextBlock();
				tb.FontSize = 14;
				tb.FontWeight = FontWeights.Bold;
				tb.Text = teamNewsItemVm.Team.Name;
				grid.Children.Add(tb);

				if (teamNewsItemVm.AllowEdit)
				{
					Button newBtn = new Button();
					newBtn.Style = (Style)FindResource("FlatButton");
					newBtn.SetValue(Grid.ColumnProperty, 1);
					newBtn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
					newBtn.Width = 16;
					newBtn.Height = 16;
					newBtn.Click += BtnCreateNewsItem_OnClick;
					newBtn.Tag = teamNewsItemVm;
					newBtn.Margin = new Thickness(0, 0, -10, 0);

					Image img = new Image();
					img.Source = new BitmapImage(new Uri(@"..\..\Ressources\Icons\new.png", UriKind.Relative));
					img.Stretch = Stretch.Uniform;
					newBtn.Content = img;
					grid.Children.Add(newBtn);
				}
				
				ex.Header = grid;
				ex.Content = sp;
				return ex;
			}
			return sp;
			
			
			//<Expander  HorizontalAlignment="Stretch" IsExpanded="True" Style="{DynamicResource FlatLineExpander}" >
			//									<Expander.Header>
			//										<Grid Background="Transparent" Visibility="{Binding Path=IsTitleVisible, Converter={StaticResource BoolVisibilityConverter}}">
			//											<Grid.ColumnDefinitions>
			//												<ColumnDefinition Width="Auto" />
			//												<ColumnDefinition Width="*" />
			//											</Grid.ColumnDefinitions>
			//											<TextBlock FontSize="14" Foreground="Black" Grid.Column="0" Grid.Row="0" FontWeight="Bold" Text="{Binding Path=Team.Name}"/>
			//											<Button Grid.Column="1" x:Name="btnCreateNewsItem" Style="{DynamicResource FlatButton}" Tag="{Binding}" Margin="0,0,-10,0"
			//													HorizontalAlignment="Right" Width="16" Height="16" Click="BtnCreateNewsItem_OnClick" Visibility="{Binding Path=AllowEdit, Converter={StaticResource BoolVisibilityConverter}}">
			//												<Image Source="..\..\Ressources\Icons\new.png" Stretch="Uniform" />
			//											</Button>

			//										</Grid>
			//									</Expander.Header>
			//									<ListBox ScrollViewer.CanContentScroll="True" IsSynchronizedWithCurrentItem="True" Margin="0,3,0,0"
			//										 Padding="0,0,0,0" Width="Auto" HorizontalAlignment="Stretch" MinWidth="0" HorizontalContentAlignment="Stretch" Background="{x:Null}" Style="{DynamicResource HomeViewListStyle}" ItemContainerStyle="{DynamicResource HomeViewListBoxItemStyle}" ScrollViewer.IsDeferredScrollingEnabled="False"
			//										 ItemsSource="{Binding Path=NewsItems}">
			//										<ListBox.ItemTemplate>
			//											<DataTemplate DataType="{x:Type shared:NewsItemDC}">
			//												<Grid Margin="0 3">
			//													<Grid.ColumnDefinitions>
			//														<ColumnDefinition Width="*" />
			//														<ColumnDefinition Width="Auto" />
			//														<ColumnDefinition Width="Auto" />
			//													</Grid.ColumnDefinitions>
			//													<Grid.RowDefinitions>
			//														<RowDefinition Height="25" />
			//														<RowDefinition Height="*" />
			//														<RowDefinition Height="Auto" />
			//													</Grid.RowDefinitions>
			//													<TextBlock FontSize="12" Foreground="{DynamicResource BigInfoTextBrush}" Grid.Column="0" Grid.Row="0" FontWeight="Bold" Text="{Binding Path=TitleString}" Margin="0,0,0,0"/>
			//													<TextBlock FontSize="10" Foreground="#FF000000" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="3" Text="{Binding Path=Text}" TextWrapping="Wrap" Margin="0,0,0,0"  />

			//													<Border Grid.Column="1" Background="Transparent">
			//													</Border>
			//													<Button Grid.Column="1" x:Name="btnEditNewsItem" BorderThickness="1,1,1,1" Padding="1,1,1,1" Style="{DynamicResource FlatButton}" Tag="{Binding}" VerticalAlignment="Top"
			//															Width="16" Height="16" Click="BtnEditNewsItem_OnClick" Visibility="Hidden">
			//														<Image Source="..\..\Ressources\Icons\edit.png" Stretch="Uniform" Margin="1,1,1,1" />
			//													</Button>


			//													<Border Grid.Column="2" Background="Transparent">
			//													</Border>
			//													<Button Grid.Column="2" x:Name="btnDeleteNewsItem" BorderThickness="1,1,1,1" Padding="1,1,1,1" Style="{DynamicResource FlatButton}" Tag="{Binding}" VerticalAlignment="Top"
			//															Width="16" Height="16" Click="BtnDeleteNewsItem_OnClick" Visibility="Hidden">
			//														<Image Source="..\..\Ressources\Icons\delete.png" Stretch="Uniform" Margin="1,1,1,1" />
			//													</Button>

			//												</Grid>
			//												<DataTemplate.Triggers>
			//													<Trigger Property="IsMouseOver" Value="True">
			//														<Setter Property="Visibility" TargetName="btnEditNewsItem" Value="{Binding Path=AllowEdit, Converter={StaticResource BoolVisibilityConverter}}" />
			//														<Setter Property="Visibility" TargetName="btnDeleteNewsItem" Value="{Binding Path=AllowEdit, Converter={StaticResource BoolVisibilityConverter}}" />
			//													</Trigger>
			//												</DataTemplate.Triggers>
			//											</DataTemplate>
			//										</ListBox.ItemTemplate>
			//									</ListBox>
			//								</Expander>
		}

		private UIElement CreateInternalNewsControl(NewsItemDC newsItem)
		{
			Grid grid = new Grid();
			grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); 
			grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
			grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });

			grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(25, GridUnitType.Pixel) });
			grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
			grid.Margin = new Thickness(0, 5, 0, 0);

			TextBlock tb = new TextBlock();
			tb.Margin = new Thickness(0, 5, 0, 0);
			tb.Foreground = new SolidColorBrush(Color.FromRgb(43, 80, 139));
			tb.Text = newsItem.TitleString;
			tb.FontSize = 12;
			tb.FontWeight = FontWeights.Bold;
			grid.Children.Add(tb);

			tb = new TextBlock();
			tb.Text = newsItem.Text;
			tb.FontSize = 10;
			tb.TextWrapping = TextWrapping.Wrap;
			tb.SetValue(Grid.RowProperty, 1);
			tb.SetValue(Grid.ColumnSpanProperty, 3);
			grid.Children.Add(tb);

			if (newsItem.AllowEdit)
			{
			//	<DataTemplate.Triggers>
			//													<Trigger Property="IsMouseOver" Value="True">
			//														<Setter Property="Visibility" TargetName="btnEditNewsItem" Value="{Binding Path=AllowEdit, Converter={StaticResource BoolVisibilityConverter}}" />
			//														<Setter Property="Visibility" TargetName="btnDeleteNewsItem" Value="{Binding Path=AllowEdit, Converter={StaticResource BoolVisibilityConverter}}" />
			//													</Trigger>
			//												</DataTemplate.Triggers>

				Border b = new Border();
				b.Background = Brushes.Transparent;
				b.SetValue(Grid.ColumnProperty, 1);
				grid.Children.Add(b);
			//	<Border Grid.Column="1" Background="Transparent">
			//													</Border>

				Button editBtn = new Button();
				editBtn.BorderThickness = new Thickness(1, 1, 1, 1);
				editBtn.Padding = new Thickness(1, 1, 1, 1);
				editBtn.Style = (Style)FindResource("FlatButton");
				editBtn.SetValue(Grid.ColumnProperty, 1);
				editBtn.VerticalAlignment = VerticalAlignment.Top;
				editBtn.Width = 16;
				editBtn.Height = 16;
				editBtn.Click += BtnEditNewsItem_OnClick;
				editBtn.Tag = newsItem;
				editBtn.Visibility = Visibility.Hidden;

				Image img = new Image();
				img.Source = new BitmapImage(new Uri(@"..\..\Ressources\Icons\edit.png", UriKind.Relative));
				img.Stretch = Stretch.Uniform;
				img.Margin = new Thickness(1, 1, 1, 1);
				editBtn.Content = img;
				grid.Children.Add(editBtn);


				b = new Border();
				b.Background = Brushes.Transparent;
				b.SetValue(Grid.ColumnProperty, 2);
				grid.Children.Add(b);

				Button deleteBtn = new Button();
				deleteBtn.Padding = new Thickness(1, 1, 1, 1);
				deleteBtn.Style = (Style)FindResource("FlatButton");
				deleteBtn.SetValue(Grid.ColumnProperty, 2);
				deleteBtn.VerticalAlignment = VerticalAlignment.Top;
				deleteBtn.Width = 16;
				deleteBtn.Height = 16;
				deleteBtn.Click += BtnDeleteNewsItem_OnClick;
				deleteBtn.Tag = newsItem;
				deleteBtn.Visibility = Visibility.Hidden;

				img = new Image();
				img.Source = new BitmapImage(new Uri(@"..\..\Ressources\Icons\delete.png", UriKind.Relative));
				img.Stretch = Stretch.Uniform;
				img.Margin = new Thickness(1, 1, 1, 1);
				deleteBtn.Content = img;
				grid.Children.Add(deleteBtn);

				grid.MouseEnter += (s, e) =>
				{
					editBtn.Visibility = Visibility.Visible;
					deleteBtn.Visibility = Visibility.Visible;
				};

				grid.MouseLeave += (s, e) =>
				{
					editBtn.Visibility = Visibility.Hidden;
					deleteBtn.Visibility = Visibility.Hidden;
				};
			}
			//<Border Grid.Column="1" Background="Transparent">
			//</Border>
			//<Button Grid.Column="1" x:Name="btnEditNewsItem" BorderThickness="1,1,1,1" Padding="1,1,1,1" Style="{DynamicResource FlatButton}" Tag="{Binding}" VerticalAlignment="Top"
			//		Width="16" Height="16" Click="BtnEditNewsItem_OnClick" Visibility="Hidden">
			//	<Image Source="..\..\Ressources\Icons\edit.png" Stretch="Uniform" Margin="1,1,1,1" />
			//</Button>
																

			//<Border Grid.Column="2" Background="Transparent">
			//</Border>
			//<Button Grid.Column="2" x:Name="btnDeleteNewsItem" BorderThickness="1,1,1,1" Padding="1,1,1,1" Style="{DynamicResource FlatButton}" Tag="{Binding}" VerticalAlignment="Top"
			//		Width="16" Height="16" Click="BtnDeleteNewsItem_OnClick" Visibility="Hidden">
			//	<Image Source="..\..\Ressources\Icons\delete.png" Stretch="Uniform" Margin="1,1,1,1" />
			//</Button>


			return grid;
		}

		private void InitLoginInfo()
		{
			DateTime endOfWeek = DateTime.Now.GetNext(DayOfWeek.Sunday).Date;

			ServiceFacade.DoAnalysisServiceAsync(s1 => s1.GetLastLogins(BeWoApp.LoggedOnUser.LoginName), ReloadLogins);
		}

		private void InitNextConferenceDates()
		{
			DateTime endOfWeek = DateTime.Now.GetNext(DayOfWeek.Sunday).Date;
			DateTime endOfWeek2 = endOfWeek.AddDays(8);

			ServiceFacade.DoAnalysisServiceAsync(s1 => s1.GetSupportConceptsWithConferenceDate(BeWoApp.LoggedOnUser.Employee.EmployeeOid, endOfWeek2), ReloadConferenceDates);
		}

		private void InitTasks()
		{
			int test = 0;
			while (BeWoApp.LoggedOnEmployee == null && test < 10)
			{
				Thread.Sleep(100);
				test++;
			}
			if (BeWoApp.LoggedOnEmployee != null)
			{
				ServiceFacade.DoAnalysisServiceAsync(s =>
					s.GetTasksForEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value),
					cb =>
					{
						this.Dispatch(delegate
						{
							if (BeWoApp.Tenant == "3057313346")
							{
								_AllTasks =
									cb.Where(
										i =>
											i.DueDate.HasValue && i.DueDate.Value.Date <= DateTime.Now.Date.AddMonths(1)).
										ToList();
							}
							else
							{
								_AllTasks = cb;
							}
							listboxTasks.ItemsSource = _AllTasks.Where(i => !i.CompletedDate.HasValue)
								.OrderBy(
									i => { return i.DueDate; }).ToList();
						});
					});
			}
		}

		private bool IsPartOf(object p, Type type)
		{
			if (p != null)
			{
				var fe = p as FrameworkElement;
				if (fe != null)
				{
					if (fe.GetType() == type)
						return true;

					return IsPartOf(fe.TemplatedParent, type);
				}
			}

			return false;
		}

		private void LoadFeed()
		{

			String url = BeWoApp.Mandator.RssFeedUrl;

			if (String.IsNullOrEmpty(url))
			{
				ServiceFacade.DoDownloadServiceAsync(
					dwn =>
					{
						try
						{
							return dwn.ReadRssFeed(null);
						}
						catch (Exception)
						{
						}

						return null;
					},
					ReloadRssFeed);
			}
			else
			{
				RssFeed feed = new RssFeed();

				RssManager mgr = new RssManager(url);
				feed.Items = mgr.GetFeed();
				feed.Title = mgr.FeedTitle;
				feed.Description = mgr.FeedDescription;

				ReloadRssFeed(feed, false);
			}
		}

		private void RadioButton_Checked(object sender, RoutedEventArgs e)
		{
			if (_AllTasks != null)
			{
				switch ((e.OriginalSource as Control).Name)
				{
					case "rb_all":
						listboxTasks.ItemsSource = _AllTasks.OrderBy(i => i.CompletedDate.HasValue ? i.CompletedDate : i.DueDate).ToList();

						break;
					case "rb_open":
						listboxTasks.ItemsSource = _AllTasks.Where(i => !i.CompletedDate.HasValue).OrderBy(i => i.DueDate).ToList();
						break;
					case "rb_closed":
						listboxTasks.ItemsSource = _AllTasks.Where(i => i.CompletedDate.HasValue).OrderByDescending(i => i.CompletedDate).ToList();
						break;
				}
			}
		}

		private void ReloadRssFeed(RssFeed feed)
		{
			ReloadRssFeed(feed, true);
		}

		private void ReloadRssFeed(RssFeed feed, bool addBeWoParameter)
		{
			if (feed != null)
			{
				if (feed.Items != null && addBeWoParameter)
				{
					foreach (RssItem rssItem in feed.Items)
					{
						if (!String.IsNullOrEmpty(rssItem.Link))
						{
							rssItem.Link += String.Format("&k={0}&s={1}", BeWoApp.Tenant, BeWoApp.ServerName);
						}
					}
				}
				this.Dispatch(delegate { listboxNews.ItemsSource = feed.Items; });
			}
		}

		private void ReloadBirthdays(List<CompactPersonDC> list)
		{
			this.Dispatch(
				delegate
				{
					list.Sort((l1, l2) => l1.DateOfBirth.Value.DayOfYear.CompareTo(l2.DateOfBirth.Value.DayOfYear));
					listboxBirthdays.ItemsSource = list;
				});
		}

		private void ReloadConferenceDates(List<CompactSupportConceptDC> list)
		{
			this.Dispatch(
				delegate
				{
					list.Sort((l1, l2) => l1.ConferenceDate.Value.CompareTo(l2.ConferenceDate.Value));
					listboxConferenceDates.ItemsSource = list;
				});
		}

		private void ReloadExpiringSupportConcepts(List<CompactSupportConceptDC> list)
		{
			this.Dispatch(
				delegate
				{
					list.Sort((l1, l2) => l1.EndDate.Value.CompareTo(l2.EndDate.Value));

					listboxExpiringSupportConcepts.ItemsSource = list;
				});
		}

		private void ReloadLogins(List<LoginDC> list)
		{
			this.Dispatch(
				delegate
				{
					// listboxNews.ItemsSource = list;
					list.Sort((l1, l2) => l1.LoginDate.Value.CompareTo(l2.LoginDate.Value));

					if (list.Count > 0)
					{
						LoginDC last = list[list.Count - 1];
						txtLoginTime.Text = "Angemeldet seit " + last.LoginDate.Value.ToShortDateString() + " " + last.LoginDate.Value.ToShortTimeString();
						if (list.Count > 1)
						{
							LoginDC dc = list[list.Count - 2];

							txtLastLoginTime.Text = ", zuletzt angemeldet am " + dc.LoginDate.Value.ToShortDateString() + " " + dc.LoginDate.Value.ToShortTimeString();
						}
					}
				});
		}

		public void ReorderPanels()
		{
			List<string> order = BeWoApp.AppSettings.StartupPanelOrder;
			if (order != null && order.Count > 0)
			{
				var panels = new Dictionary<string, DragDockPanel>();

				foreach (object item in panelHost.Children)
				{
					var p = item as DragDockPanel;
					panels.Add(p.Name, p);
				}

				panelHost.Children.Clear();
				foreach (string item in order)
				{
					if (panels.ContainsKey(item))
					{
						DragDockPanel p = panels[item];

						panelHost.AddPanel(p); // Children.Add(p);

						panels.Remove(item);
					}
				}

				foreach (DragDockPanel item in panels.Values)
				{
					panelHost.AddPanel(item);
				}
			}
		}

		private void SetMaximizedPanel()
		{
			if (!String.IsNullOrEmpty(BeWoApp.AppSettings.StartupPanelMaximized))
			{
				foreach (object item in panelHost.Children)
				{
					var p = item as DragDockPanel;
					if (BeWoApp.AppSettings.StartupPanelMaximized.Equals(p.Name))
					{
						IEnumerable<DependencyObject> objekts = p.GetAllChildren();

						foreach (DependencyObject child in objekts)
						{
							if (child is ToggleButton)
							{
								var btn = child as ToggleButton;
								btn.IsChecked = true;
							}
						}
					}
				}
			}
		}

		private void listboxBirthdays_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (!IsPartOf(e.OriginalSource, typeof (ScrollBar)))
			{
				var dc = ((ListBox) sender).SelectedItem as CompactPersonDC;

				if (dc != null)
				{
					if (dc.PersonType == PersonType.Customer)
					{
						if (BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll))
						{
							ServiceFacade.DoCustomerServiceAsync(
								s => s.GetCustomerWithPersonOid(dc.PersonOid),
								cb => VMFactory.CreateCustomerVMAsync(
									cb,
									cb2 => this.Dispatch(
										delegate
										{
											MainControl.NavigateTo(
												new CustomerView(cb2)
												{
													ParentView = this
												});
										})));
						}
					}
					else if (dc.PersonType == PersonType.Employee)
					{
						if (BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll))
						{
							ServiceFacade.DoEmployeeServiceAsync(
								s => s.GetEmployeeWithPersonOid(dc.PersonOid),
								cb => VMFactory.CreateEmployeeVMAsync(
									cb,
									cb2 => this.Dispatch(
										delegate
										{
											MainControl.NavigateTo(
												new EmployeeView(cb2)
												{
													ParentView = this
												});
										})));
						}
					}
					else if (BeWoApp.LoggedOnUser.HasRight(UserRightType.PersonView_View) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll))
					{
						VMFactory.CreatePersonVMAsync(
							dc.PersonOid,
							cb => this.Dispatch(
								delegate
								{
									MainControl.NavigateTo(
										new PersonView(cb)
										{
											ParentView = this
										});
								}));
					}
				}
			}
		}

		private void listboxSupportConcepts_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (!IsPartOf(e.OriginalSource, typeof (ScrollBar)))
			{
				var sc = ((ListBox) sender).SelectedItem as CompactSupportConceptDC;

				if (sc != null &&
				    (BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_ViewAllSupportConcepts) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll) ||
				     BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_View)))
				{
					VMFactory.CreateSupportConceptVMAsync(
						sc.SupportConceptOid,
						cb => this.Dispatch(
							delegate
							{
								MainControl.NavigateTo(new SupportConceptView(cb) {ParentView = this});
								//new SupportConceptView2(cb)
								//        {
								//            ParentView = this
								//        });
							}));
				}
			}
		}

		private void listboxTasks_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (!IsPartOf(e.OriginalSource, typeof (ScrollBar)))
			{
				var sc = ((ListBox) sender).SelectedItem as TaskDC;

				if (sc != null &&
				    (BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_ViewAllSupportConcepts) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll) ||
				     BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_View)))
				{
					VMFactory.CreateSupportConceptVMAsync(
						sc.SupportConceptOid.Value,
						cb => this.Dispatch(
							delegate
							{
								MainControl.NavigateTo(
									new SupportConceptView(cb, sc)
									{
										ParentView = this
									});
								//new SupportConceptView2(cb)
								//{
								//    ParentView = this
								//});
							}));
				}
			}
		}

		// private void FillOutbox()
		// {
		// if (BeWoApp.LoggedOnUser.Employee != null)
		// {
		// BeWo.ServiceProxy.ServiceFacade.DoMailServiceAsync(
		// s => s.GetOutgoingMails(BeWoApp.LoggedOnUser.Employee.EmployeeOid),
		// result => this.Dispatcher.BeginInvoke(new Call(delegate()
		// {
		// outboxList.ItemsSource = result;
		// }))
		// );

		// }
		// }

		// private void FillInbox()
		// {
		// if (BeWoApp.LoggedOnUser.Employee != null)
		// {

		// BeWo.ServiceProxy.ServiceFacade.DoMailServiceAsync(
		// s => s.GetIncomingMails(BeWoApp.LoggedOnUser.Employee.EmployeeOid),
		// result => this.Dispatcher.BeginInvoke(new Call(delegate()
		// {
		// text.Text = GenerateMailText(result);
		// inboxList.ItemsSource = result;
		// }))
		// );
		// }
		// }

		// delegate void Call();

		// private static string GenerateMailText(List<MailDC> result)
		// {
		// //var builder = new StringBuilder();

		// //var unreadMails = result.Where(r => r.Status == null || r.Status == Status.unread).Count();
		// //builder.AppendLine("Sie haben " + unreadMails + "/" + result.Count + " Mails");

		// //foreach (var item in result)
		// //{
		// //    builder.AppendLine(item.Subject);
		// //}

		// //return builder.ToString();

		// var unreadMails = result.Where(r => r.Status == null || r.Status == Status.unread).Count();
		// return "Sie haben " + unreadMails + "/" + result.Count + " Mails";

		// }

		// private void ButtonNew_Click(object sender, RoutedEventArgs e)
		// {
		// OpenSendMailView();
		// //   throw new NotImplementedException();
		// }

		// private void OpenSendMailView()
		// {
		// BeWoApp.MainControl.NavigateTo(new SendMailView() { ParentView = this });
		// //throw new NotImplementedException();
		// }

		// private void ButtonReplyNew_Click(object sender, RoutedEventArgs e)
		// {
		// if (boxTabControl.SelectedIndex == 0)
		// {
		// if (inboxList.SelectedIndex < 0)
		// {
		// MessageBox.Show("Sie haben keine Nachricht ausgewählt");
		// return;
		// }

		// var mailDC = inboxList.SelectedItem as MailDC;

		// BeWoApp.MainControl.NavigateTo(new SendMailView(SendMailView.Mode.Reply, mailDC));
		// }
		// else
		// {
		// MessageBox.Show("Sie können nicht auf Ihre eigene Mail antworten");
		// }
		// }

		// private void ButtonForward_Click(object sender, RoutedEventArgs e)
		// {
		// if (boxTabControl.SelectedIndex == 0)
		// {
		// if (inboxList.SelectedIndex < 0)
		// {
		// MessageBox.Show("Sie haben keine Nachricht ausgewählt");
		// return;
		// }

		// var mailDC = inboxList.SelectedItem as MailDC;

		// BeWoApp.MainControl.NavigateTo(new SendMailView(SendMailView.Mode.Forward, mailDC));
		// }
		// else
		// {
		// MessageBox.Show("Sie können Ihre eigene Mail nicht wieterleiten");
		// }
		// }

		// private void ButtonDelete_Click(object sender, RoutedEventArgs e)
		// {
		// if (boxTabControl.SelectedIndex == 0)
		// {
		// if (inboxList.SelectedIndex < 0)
		// {
		// MessageBox.Show("Sie haben keine Nachricht ausgewählt");
		// return;
		// }

		// var mailDC = inboxList.SelectedItem as MailDC;

		// BeWo.ServiceProxy.ServiceFacade.DoMailServiceAsync(s => s.DeleteMail(BeWoApp.LoggedOnUser.Employee.EmployeeOid, mailDC));

		// //inboxList.ItemsSource.RemoveAt(inboxList.SelectedIndex);
		// FillInbox();
		// }
		// else
		// {
		// MessageBox.Show("Outbox funktioniert noch nicht");

		// //BeWo.ServiceProxy.ServiceFacade.DoMailServiceAsync(s => s.DeleteMail(BeWoApp.LoggedOnUser.Employee.EmployeeOid, outboxList.SelectedItem as MailDC);
		// }

		// //throw new NotImplementedException();
		// }

		// private void InboxItem_DoubleClick(object sender, RoutedEventArgs e)
		// {
		// var listboItem = sender as ListBoxItem;
		// var content = listboItem.Content as MailDC;

		// MainControl.NavigateTo(new ViewMailView(content) { ParentView = this });

		// //throw new NotImplementedException();
		// }

		// private void OutboxItem_DoubleClick(object sender, RoutedEventArgs e)
		// {
		// var listboItem = sender as ListBoxItem;
		// var content = listboItem.Content as MailDC;

		// MainControl.NavigateTo(new ViewMailView(content) { ParentView = this });
		// }
		private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
		{
			Process.Start(new ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()));
		}

		private delegate void loadFeed(string url);

		private void PasswortAendernLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
		{
			var pav = new PasswortAenderungsView();
			pav.ShowDialog();
		}

        private void ChatLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            chatpav.Visibility = Visibility.Visible;
                    chatpav.SetText(chat.Text,"NULL", 0);
        }


		private void BtnCreateNewsItem_OnClick(object sender, RoutedEventArgs e)
		{
			TeamNewsItemVM  teamVm = ((Button)sender).Tag as TeamNewsItemVM;
			if (teamVm != null)
			{
				NewsItemDC dc = new NewsItemDC();
				dc.PublishDate = DateTime.Now;
				dc.Team = teamVm.Team;

				NewsItemVM vm = new NewsItemVM(dc);
				var ctrl = new NewsItemEditControl(vm);

				BeWoWindow window = BeWoWpfUtils.CreateBeWoPopupWindow(400, 500);
				window.GroupBoxContent = ctrl;
				window.Height = 400;
				window.Owner = BeWoApp.CurrentBeWo.MainWindow;
				//ThemeManager.SetTheme(window, Theme.Office2010Black);

				ctrl.CancelButtonClicked += window.Close;
				ctrl.OkButtonClicked += () => 
				{
					SaveNewsItem(vm);
					window.Close();
				};


				window.rootGroupBox.Header = "Neuer Eintrag";
				window.Title = "Neuer Eintrag";
				window.Show();

			}
		}

		private void SaveNewsItem(NewsItemVM vm)
		{
			ServiceFacade.DoEmployeeServiceSync(s => s.InsertNewNewsItem(vm.CommitToDataContract()));
			UpdateInternalNews();
		}


		private void BtnEditNewsItem_OnClick(object sender, RoutedEventArgs e)
		{
			NewsItemDC dc = ((Button)sender).Tag as NewsItemDC;
			if (dc != null)
			{
				NewsItemVM vm = new NewsItemVM(dc);
				var ctrl = new NewsItemEditControl(vm);

				BeWoWindow window = BeWoWpfUtils.CreateBeWoPopupWindow(400, 500);
				window.GroupBoxContent = ctrl;
				window.Height = 400;
				window.Owner = BeWoApp.CurrentBeWo.MainWindow;
				//ThemeManager.SetTheme(window, Theme.Office2010Black);
				ctrl.CancelButtonClicked += window.Close;
				ctrl.OkButtonClicked += () =>
				{
					UpdateNewsItem(vm);
					window.Close();
				};

				window.rootGroupBox.Header = "Eintrag bearbeiten";
				window.Title = "Eintrag bearbeiten";
				window.Show();
				
			}
		}

		private void UpdateNewsItem(NewsItemVM vm)
		{
			ServiceFacade.DoEmployeeServiceSync(s => s.UpdateNewsItem(vm.CommitToDataContract()));
			UpdateInternalNews();
		}

		private void BtnDeleteNewsItem_OnClick(object sender, RoutedEventArgs e)
		{
			NewsItemDC dc = ((Button)sender).Tag as NewsItemDC;
			if (dc != null)
			{
				if (MessageBox.Show("Wollen Sie den Eintrag '" + dc.Title + "' wirklich löschen?", "Löschen bestätigen",
						MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
				{
					ServiceFacade.DoEmployeeServiceSync(s => s.DeleteNewsItem(dc.NewsItemOid.Value, dc.NewsItemVersion.Value));

					UpdateInternalNews();
				}
			}
		}


        //#################### Serveranwendung System ##################################################
        public void onConnectionStart()
        {
            try
            {
                int port = 5000;
                String ipAdresse = "127.0.0.1";

                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                //ipAdressvergabe falls gewollt
                //IPEndPoint iplocal = new IPEndPoint(IPAddress.Parse(ipAdresse),port);
                IPEndPoint iplocal = new IPEndPoint(IPAddress.Any, port);

                m_mainSocket.Bind(iplocal);

                m_mainSocket.Listen(4);

                m_mainSocket.BeginAccept(new AsyncCallback(OnConnectedClient), null);

            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        //Zählt und (erstellt Sockets) der jeweiligen anfragen der clienten,  
        public void OnConnectedClient(IAsyncResult asn)
        {
            try
            {
               // if (m_mainSocket.Connected){    <------- Hier muss ordentliche abfrage hin sonst schmiert das ding beim abmelden ab.
                    Socket workerSocket = m_mainSocket.EndAccept(asn);
                
                Interlocked.Increment(ref clientCount);

                m_workerSocketList.Add(workerSocket);
                
                WaitforDatenfromClient(workerSocket, clientCount, "", 0);

                m_mainSocket.BeginAccept(new AsyncCallback(OnConnectedClient), null);

               //}
            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
            }
        }


        //Listener der immer auf eine Antwort vom Clienten wartet
        public void WaitforDatenfromClient(Socket soc, int clientnummer, String clientname, long oid)
        {
            try
            {
                if (asyncWorkerCallBack == null)
                {
                    asyncWorkerCallBack = new AsyncCallback(OnReceiveData);
                }

                SocketPacket sockPac = new SocketPacket(soc, clientnummer, clientname,oid);

                soc.BeginReceive(sockPac.dataBuffer, 0, sockPac.dataBuffer.Length, SocketFlags.None, asyncWorkerCallBack, sockPac);

            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        //Verarbeitet vom Clienten Erhaltene Daten  
        public void OnReceiveData(IAsyncResult asn)
        {
            socketDaten = (SocketPacket)asn.AsyncState;

            //primitiv aber effektiv mit bugs deshalb ungenutzt
              Boolean erstkonntakt = false;

            try
            {

                int anzahlre = socketDaten.m_currentSocket.EndReceive(asn);
                char[] chars = new char[anzahlre];

                Decoder decode = System.Text.Encoding.UTF8.GetDecoder();

                int charLenght = decode.GetChars(socketDaten.dataBuffer, 0, anzahlre, chars, 0);

                erhaltenerDS = new String(chars);


                string msg = "" + socketDaten.m_clientNumber + ":";

                // Send back the reply to the client
                //string replyMsg = "Server Reply:" + erhaltenerDS.ToUpper();
                // Convert the reply to byte array
                //byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);

                Socket workerSocket = (Socket)socketDaten.m_currentSocket;

                #region save socketdaten daten für chat bereich
                //######################### Fische den Namen des Clienten Raus und weise ihm am ende zu ################ 
                if (socketDaten.m_clientname.ToString().Equals(""))
                {
                    int x;

                    int persOid = 0;

                    String[] splitt = erhaltenerDS.Split('/');
                    
                    //Hole die Person oid aus dem Connection String 
                    String[] personoid = splitt[1].Split('?');
                   
                    if (splitt.Length > 1)
                    {
                         Int32.TryParse(splitt[1], out x);
                         bool isNum = false;
                         // so oder soetwa muss das gehen 
                        if (personoid.Length > 1)
                        {                         
                            isNum = Int32.TryParse(personoid[1], out persOid);
                            Console.WriteLine("" + persOid);
                        }

                        if (isNum)
                        {
                            socketDaten.m_clientname = splitt[0];


                            Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            (ThreadStart)delegate { //Clientlist.Items.Add(socketDaten.m_clientname);


                            if (persOid != 0)
                                socketDaten.m_clientpersonoid = persOid; 


                            chatpav.SetList(socketDaten.m_clientname,socketDaten.m_clientpersonoid,socketDaten.m_clientNumber);
                            chatpav.SetServerStats(splitt[0] + " Connected");

                            //statt "" war erhalteneDS | neu hinzugefügt
                            pav = new MiniChatView(socketDaten.m_clientname, "", chatpav,socketDaten.m_clientpersonoid);
                            pav.Visibility = Visibility.Collapsed;


                                //Abfrage bei gkleiche Schlüssel weil sonst crash
                            pavlist.Add(socketDaten.m_clientname, pav);
                            });


                            erstkonntakt = true;
                            erhaltenerDS = splitt[0] + " Connected";


                            // Send back the reply to the client
                            string replyMsg = BeWoApp.LoggedOnUser.LoginName + ":" + " Connected" + "\n";
                            // Convert the reply to byte array
                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);


                            Socket workerS = (Socket)socketDaten.m_currentSocket;
                            workerS.Send(byData);

                        }
                        else
                        {
                            socketDaten.m_clientname = "Client";

                            Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            (ThreadStart) delegate
                            {
                               // Clientlist.Items.Add("Client" + clientCount);
                                chatpav.SetList("Client" + clientCount,socketDaten.m_clientpersonoid,socketDaten.m_clientNumber);
                                chatpav.SetServerStats("Client" + clientCount + " Connected"); 
                                
                                //statt "" war erhalteneDS | neu hinzugefügt
                                pav = new MiniChatView(socketDaten.m_clientname + clientCount, "", chatpav,socketDaten.m_clientpersonoid);
                                pav.Visibility = Visibility.Collapsed;

                                pavlist.Add(socketDaten.m_clientname + clientCount, pav);
                            });

                            erstkonntakt = true;

                            // Send back the reply to the client
                            string replyMsg = BeWoApp.LoggedOnUser.LoginName + ":" + " Connected" + "\n";
                            // Convert the reply to byte array
                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);


                            Socket workerS = (Socket)socketDaten.m_currentSocket;
                            workerS.Send(byData);

                        }

                    }
                    else
                    {
                        socketDaten.m_clientname = "Client";

                        Dispatcher.Invoke(
                        DispatcherPriority.Normal,
                        (ThreadStart) delegate
                        {
                            //Clientlist.Items.Add("Client" + clientCount);
                            chatpav.SetList("Client" + clientCount,socketDaten.m_clientpersonoid,socketDaten.m_clientNumber);
                            chatpav.SetServerStats("Client" + clientCount + " Connected");
                            //statt "" war erhalteneDS | neu hinzugefügt
                            pav = new MiniChatView(socketDaten.m_clientname + clientCount, "", chatpav,socketDaten.m_clientpersonoid);
                            pav.Visibility = Visibility.Collapsed;

                            pavlist.Add(socketDaten.m_clientname + clientCount, pav);
                        });
                        erstkonntakt = true;

                        // Send back the reply to the client
                        string replyMsg = BeWoApp.LoggedOnUser.LoginName + ":" + " Connected " + "\n";
                        // Convert the reply to byte array
                        byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);


                        Socket workerS = (Socket)socketDaten.m_currentSocket;
                        workerS.Send(byData);
                        
                    }
                    //#####################################################################################################
                }
#endregion
              
                #region verarbeite erhaltene Daten
                // if (!erstkonntakt)
               // {
                    //###################################### Message bereich ###################################################
                    //hier die aufforderung die nachrichten an alle anderen clienten zu schicken  // Später umfunktioniert zu senden Klient / klienten              
                    if (!erhaltenerDS.Equals(""))
                    {
                        SendMessageToOtherClients(erhaltenerDS, socketDaten.m_clientNumber);
                    }

                    //aktualiesiere die gui
                    if (!erhaltenerDS.Equals(""))
                    {

                        //Hier abfrage ob ehlateneDaten  == Socketname dann soll maybe nix passieren/ erstellen wen gewünscht  

                        Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            (ThreadStart) delegate
                            {
                                chat.AppendText(socketDaten.m_clientname + ": " + erhaltenerDS + "\n");
                                chat.ScrollToEnd();

                                if (chatpav.Visibility != Visibility.Visible &&
                                    pavlist[socketDaten.m_clientname].Visibility != Visibility.Visible)
                                {
                                    pavlist[socketDaten.m_clientname].Visibility = Visibility.Visible;
                                    pavlist[socketDaten.m_clientname].SetText(erhaltenerDS, 1);
                                }
                                else if (pavlist[socketDaten.m_clientname].Visibility != Visibility.Visible)
                                {
                                    chatpav.SetText(erhaltenerDS, socketDaten.m_clientname,socketDaten.m_clientpersonoid);
                                }
                                else
                                {
                                    pavlist[socketDaten.m_clientname].AppendTextwhileViewOpen(erhaltenerDS, 1);
                                }

                            });

                        //Continue Waiting for data on The Current socket
                        WaitforDatenfromClient(socketDaten.m_currentSocket, socketDaten.m_clientNumber,
                            socketDaten.m_clientname,socketDaten.m_clientpersonoid);
                    }
                    else
                    {
                            //primitiv aber funktioniert entfernt den current client
                            Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            (ThreadStart) delegate
                            {


                                if (!socketDaten.m_clientname.Equals("Client"))
                                {

                                    chatpav.RemoveListItem(socketDaten.m_clientpersonoid);

                                    chatpav.SetServerStats(socketDaten.m_clientname + " Disconnected ! ");

                                    pavlist.Remove(socketDaten.m_clientname);

                                    m_workerSocketList[socketDaten.m_clientNumber - 1] = null;
                                    workerSocket.Close();

                                }
                                else
                                {
                                    chatpav.RemoveListItem(socketDaten.m_clientpersonoid);
                                    chatpav.SetServerStats(socketDaten.m_clientname + socketDaten.m_clientNumber +
                                                           " Disconnected ! ");

                                    //Removed die dazugehörige Minichatview
                                    pavlist.Remove(socketDaten.m_clientname);

                                    m_workerSocketList[socketDaten.m_clientNumber - 1] = null;
                                    workerSocket.Close();
                                }
                            });
                //###################################### Message bereich Ende ###################################################
                    }
#endregion


            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnReceiveData: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);

                if (se.ErrorCode == 10054) // Error code for Connection reset 
                {
                    m_workerSocketList[socketDaten.m_clientNumber - 1] = null;
                }
            }

        }

        //erstellt den Current Socket und legt die Größe fest
        public class SocketPacket
        {
            public Socket m_currentSocket;
            public int m_clientNumber;
            public String m_clientname;
            public long m_clientpersonoid;

            // Buffer to store the data sent by the client
            public byte[] dataBuffer = new byte[1024];

            public SocketPacket(Socket socket, int clientNummer, String name,long oid)
            {
                m_currentSocket = socket;
                m_clientNumber = clientNummer;
                m_clientname = name;
                m_clientpersonoid = oid;
            }
        }

        //Sende Nachrichten von Client an alle anderen clienten
        public void SendMessageToOtherClients(String msg, int curClient)
        {
            try
            {
                msg = "Client " + curClient + ": " + msg + "\n";
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
                Socket workerSocket = null;
            
                int x = 1;
                for (int i = 0; i < m_workerSocketList.Count; i++)
                {

                    if (x != curClient)
                    {
                        workerSocket = (Socket)m_workerSocketList[i];
                        if (workerSocket != null)
                        {
                            if (workerSocket.Connected)
                            {
                                workerSocket.Send(byData);
                            }
                        }
                    }
                    else
                    {
                        //Console.WriteLine("I ist gleich curent Client");
                    }
                    x++;
                }

                //Console.WriteLine("Entweder Erfolgreich oder halt aber nicht");

            }
            catch (Exception xe)
            {
                Dispatcher.Invoke(
                DispatcherPriority.Normal,
                (ThreadStart)delegate { chatpav.SetServerStats("Ein Fehler im Bereich Message"); });

            }

        }


        public void CloseConnection()
        {
            try
            {
                if (m_mainSocket != null)
                {
                    m_mainSocket.Close();
                }

                Socket workerSocket = null;
                for (int i = 0; i < m_workerSocketList.Count; i++)
                {
                    workerSocket = (Socket)m_workerSocketList[i];
                    if (workerSocket != null)
                    {

                        workerSocket.Close();
                        //workerSocket = null;
                    }
                }
            }
            catch (Exception ze)
            {
                Dispatcher.Invoke(
                DispatcherPriority.Normal,
                (ThreadStart)delegate { ServerStats.Text = "Ein Fehler im Bereich Schließen"; });
            }
        }

        //####################### Close Connection den Abmelde Button anfügen ###############################




	}

	public class TaskDateDescriptionConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var task = value as TaskDC;
			if (task != null)
			{
				if (task.CompletedDate.HasValue)
					return string.Format("erledigt am: {0:d}", task.CompletedDate);
				if (task.DueDate.HasValue)
					return string.Format("bis {0:d} {0:t}", task.DueDate, task.DueDate);
			}
			return string.Empty;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}