using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

using BeWo.Annotations;
using BeWo.Scheduler.Resources;
using BeWo.Scheduler.ViewModel;
using BeWo.ServiceProxy;
using BeWo.View;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;

using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Scheduler;
using DevExpress.XtraScheduler;

namespace BeWo.Scheduler.View
{
	// Verschieben von Geburtstag / Ende von Hilfeplänen -> Meldung, man soll es im entsprechenden Menü machen
    public partial class SchedulerView : INotifyPropertyChanged
    {
	    private const string FilterAbwesenheiten = "Abwesenheiten";
		private const string FilterGeburtstage = "Geburtstage";
		private const string FilterHilfeplaene = "Hilfepläne";
	    private const string FilterKein = "Kein";
		private const string FilterKlienten = "Klienten";
		private const string FilterMitarbeiter = "Mitarbeiter";
	    private const string FilterRessourcen = "Ressourcen";
		private const string FilterRessourcenkategorien = "Ressourcenkategorien/Ressourcen";

	    private CompactEmployeeDC selectedEmployee;
	    private CompactCustomerDC selectedCustomer;
	    private ResourceDC selectedResource;

        private bool mIgnoreChangeEvents;

        private AppointmentKind _Terminart;
        public AppointmentKind Terminart
        {
            get { return _Terminart; }
            set
            {
                _Terminart = value;

			    Filter1BoxEdit.SelectedItem = FilterKein;
			    NachKlientenGruppieren.Visibility = Visibility.Hidden;

                BeiEigenschaftsAaenderung("Terminart");
            }
        }

        public SchedulerView()
        {
            InitializeComponent();
			
            DataContext = this;

            InitRights();
            InitScheduler();
            InitViewModel();
			Scheduler.ApplyTemplate();

            Scheduler.PopupMenuShowing += Scheduler_PopupMenuShowing;
	        Scheduler.Storage.FilterResource += SchedulerStorage_FilterResource;
            LoadFilterLists();
	        NachKlientenGruppieren.Visibility = Visibility.Hidden;

	        Scheduler.Storage.AppointmentStorage.ResourceSharing = false;
        }

		private void SchedulerStorage_FilterResource(object sender, PersistentObjectCancelEventArgs e)
		{
			var res = (Resource)e.Object;
			if (!Terminart.Equals(AppointmentKind.Employee) || !PopupeditEmployee.Visibility.Equals(Visibility.Visible))
			{
				e.Cancel = false;
				return;
			}

			e.Cancel = !res.Id.Equals(selectedEmployee.EmployeeOid);
		}

        private SchedulerViewType currentViewType;

        private Dictionary<string, List<IDataContract>> _AppointmentFilterLists;

        private void Filter1BoxEditLoadFilterOptions()
        {
            this.Dispatch(() =>
            {
                switch (Terminart)
                {
                    case AppointmentKind.Resource:
                        Filter1BoxEdit.ItemsSource = new List<string> { FilterKein, FilterMitarbeiter, FilterRessourcenkategorien };
                        break;
                    case AppointmentKind.Employee:
						Filter1BoxEdit.ItemsSource = new List<string> { FilterKein, FilterMitarbeiter };
                        break;
					case AppointmentKind.CommonCalendar:
						Filter1BoxEdit.ItemsSource = new List<string> { FilterKein, FilterAbwesenheiten, FilterGeburtstage, FilterHilfeplaene, FilterKlienten };
		                break;
					case AppointmentKind.Customer:
						Filter1BoxEdit.ItemsSource = new List<string> { FilterKein, FilterKlienten };
		                break;
                    default:
                        FilterLabel.Visibility = Visibility.Collapsed;
                        Filter1BoxEdit.Visibility = Visibility.Collapsed;
                        Filter2BoxEdit.Visibility = Visibility.Collapsed;
                        return;
                }

                if (Filter1BoxEdit.ItemsSource == null || !((IEnumerable<object>) Filter1BoxEdit.ItemsSource).Any())
                    return;

		        Filter1BoxEdit.SelectedIndex = 0;
                Filter2BoxEdit.IsEnabled = false;
                FilterLabel.Visibility = Visibility.Visible;
                Filter1BoxEdit.Visibility = Visibility.Visible;
				ListBoxResources.Visibility = Visibility.Hidden;
            });
        }

        private void Filter1BoxEdit_EditValueChanged(object sender, EventArgs e)
        {
            var cbe = (ComboBoxEdit)sender;
            if (cbe == null) return;

	        Filter2BoxEdit.ItemsSource = new List<object>();

			Filter2BoxEdit.Visibility = Visibility.Hidden;
			ListBoxResources.Visibility = Visibility.Hidden;
			PopupeditCustomer.Visibility = Visibility.Hidden;
			PopupeditEmployee.Visibility = Visibility.Hidden;

	        PopupeditCustomer.Text = string.Empty;
			PopupeditEmployee.Text = string.Empty;

            switch (cbe.SelectedItem.ToString())
            {
				case FilterMitarbeiter:
		            PopupeditEmployee.Visibility = Visibility.Visible;
                    break;
				case FilterRessourcenkategorien:
					Filter2BoxEdit.ItemsSource = _AppointmentFilterLists[FilterRessourcenkategorien];
					Filter2BoxEdit.Visibility = Visibility.Visible;
					ListBoxResources.Visibility = Visibility.Visible;
					UpdateListBoxResourcesItemsSource();
                    break;
				case FilterKlienten:
					PopupeditCustomer.Visibility = Visibility.Visible;
                    break;
				case FilterKein:
                    Filter2BoxEdit.ItemsSource = null;
                    Filter2BoxEdit.EditValue = null;
                    Filter2BoxEdit.IsEnabled = false;
		            PopupeditCustomer.Text = string.Empty;
					PopupeditEmployee.Text = string.Empty;
					
                    Scheduler.ActiveView.LayoutChanged();
                    return;
				case FilterGeburtstage:
					Scheduler.ActiveView.LayoutChanged();
                    return;
				case FilterHilfeplaene:
					Scheduler.ActiveView.LayoutChanged();
                    return;
				case FilterAbwesenheiten:
					Scheduler.ActiveView.LayoutChanged();
		            return;
                default:
                    return;
            }

            Filter2BoxEdit.IsEnabled = true;
		    Filter2BoxEdit.SelectedIndex = 0;
        }

        private void Filter2BoxEdit_EditValueChanged(object sender, EventArgs e)
        {
			UpdateListBoxResourcesItemsSource();
        }

        private void Scheduler_PopupMenuShowing(object sender, SchedulerMenuEventArgs e)
        {
            if (!Terminart.Equals(AppointmentKind.Resource)) return;

            foreach (var item in e.Menu.ItemLinks)
            {
                var bil = item as BarItemLink;

                if (bil == null) continue;

                var biName = bil.BarItemName;
                if (biName.Equals("NewAllDayEvent") ||
                    biName.Equals("NewRecurringEvent"))
                {
                    item.IsVisible = false;
                }
            }
        }

        private void LoadFilterLists()
        {
            _AppointmentFilterLists = new Dictionary<string, List<IDataContract>>();
			ServiceFacade.DoEmployeeServiceAsync(es => es.GetAllActiveEmployeesCompact(), a => this.Dispatch(() => _AppointmentFilterLists.Add(FilterMitarbeiter, new List<IDataContract>(a.ToList()))));
			ServiceFacade.DoResourceServiceAsync(es => es.GetAllResources(), a => this.Dispatch(() => _AppointmentFilterLists.Add(FilterRessourcen, new List<IDataContract>(a.ToList()))));
			ServiceFacade.DoValueListServiceAsync(es => es.GetAllValueListEntrysByType(ValueListEntryType.ResourceCategory), a => this.Dispatch(() => _AppointmentFilterLists.Add(FilterRessourcenkategorien, new List<IDataContract>(a.ToList()))));
			ServiceFacade.DoCustomerServiceAsync(cs => cs.GetAllActiveCustomersCompact(false, null), a => this.Dispatch(() => _AppointmentFilterLists.Add(FilterKlienten, new List<IDataContract>(a.ToList()))));
        }

        public SchedulerViewModel ViewModel { get; set; }

        public override bool IsDirty
        {
            get { return false; }
        }

        private void InitViewModel()
        {
            ViewModel = new SchedulerViewModel();
            ViewModel.ViewModelChanged += ViewModel_ViewModelChanged;
        }

        private void ViewModel_ViewModelChanged(object sender, EventArgs<ISchedulerViewModel> e)
        {
            Filter1BoxEditLoadFilterOptions();
			this.Dispatch(() => UpdateDataSource(e.Data));
        }

        private void UpdateDataSource(ISchedulerViewModel vm)
        {
            UpdateCustomFieldMappings(vm);
            
            UpdateAppointmentLabels(vm.Categories);
			Scheduler.Storage.AppointmentStorage.DataSource = vm.Appointments;
			UpdateSchedulerSettings();
            Scheduler.Storage.ResourceStorage.DataSource = vm.Resources;

            mIgnoreChangeEvents = true;
			
            foreach (Appointment item in Scheduler.Storage.AppointmentStorage.Items)
            {
                var bapp = item.GetSourceObject(Scheduler.GetCoreStorage()) as IBeWoAppointment;

                if (bapp == null || bapp.CustomFields == null) continue;

                foreach (var field in bapp.CustomFields)
                    item.CustomFields[field.Key] = field.Value;
            }
			
            mIgnoreChangeEvents = false;
        }

        private void UpdateCustomFieldMappings(ISchedulerViewModel vm)
        {
            Scheduler.Storage.AppointmentStorage.CustomFieldMappings.Clear();
            vm.AddCustomFieldsMapping(Scheduler.Storage);
        }

        private void UpdateAppointmentLabels(IEnumerable<BeWoAppointmentCategory> iList)
        {
            Scheduler.Storage.AppointmentStorage.Labels.Clear();

            if (iList != null)
            {
                foreach (var item in iList)
                {
                    var lbl = new AppointmentLabel
                    {
                        Color = item.Color,
                        DisplayName = item.DisplayName,
                        MenuCaption = item.MenuCaption
                    };

                    Scheduler.Storage.AppointmentStorage.Labels.Add(lbl);
                }
            }
        }

        private void InitScheduler()
        {
            Scheduler.Start = DateTime.Now;

            Scheduler.DayView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
            Scheduler.DayView.AppointmentDisplayOptions.ShowRecurrence = true;
            Scheduler.DayView.AppointmentDisplayOptions.ShowReminder = true;
            Scheduler.DayView.ResourcesPerPage = 3;

            Scheduler.WorkWeekView.ShowFullWeek = false;
            Scheduler.WorkWeekView.ShowWorkTimeOnly = false;
            Scheduler.WorkWeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
            Scheduler.WorkWeekView.ResourcesPerPage = 3;

            Scheduler.WeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
            Scheduler.WeekView.ResourcesPerPage = 3;

            Scheduler.MonthView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
            Scheduler.MonthView.ResourcesPerPage = 3;

            Scheduler.TimelineView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
            Scheduler.TimelineView.ResourcesPerPage = 0;
        }

        private void UpdateSchedulerSettings()
        {
            SchedulerSettings settings = ViewModel.GetActiveSettings();

            Scheduler.Start = settings.StartDate;
            DateTime starttimeInterval = settings.StartDate.Date;
            starttimeInterval = starttimeInterval.AddHours(Scheduler.WorkWeekView.WorkTime.Start.Hours);

            switch (settings.ViewType)
            {
                case AppointmentViewType.Day:
                    Scheduler.ActiveViewType = SchedulerViewType.Day;
                    Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
                    Scheduler.DayView.DayCount = settings.DayViewCount;
                    break;
                case AppointmentViewType.Week:
                    Scheduler.ActiveViewType = SchedulerViewType.Week;
                    Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
                    break;
                case AppointmentViewType.Month:
                    Scheduler.ActiveViewType = SchedulerViewType.Month;
                    break;
                case AppointmentViewType.WorkWeek:
                    Scheduler.ActiveViewType = SchedulerViewType.WorkWeek;
                    Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
                    break;
                case AppointmentViewType.Timeline:
                    Scheduler.ActiveViewType = SchedulerViewType.Timeline;
                    Scheduler.TimelineView.ResourcesPerPage = settings.TimelineResourceCount;
                    Scheduler.TimelineView.IntervalCount = settings.TimelineIntervalCount;
                    break;
            }

            UpdateOptionPanel(settings.ViewType);

	        try
	        {
		        Scheduler.GroupType = settings.GroupByResource ? SchedulerGroupType.Resource : SchedulerGroupType.None;

				Scheduler.OptionsCustomization.AllowAppointmentDelete = settings.AllowDelete
					? UsedAppointmentType.Custom
					: UsedAppointmentType.None;
				Scheduler.OptionsCustomization.AllowAppointmentEdit = settings.AllowEdit
					? UsedAppointmentType.Custom
					: UsedAppointmentType.None;
				Scheduler.OptionsCustomization.AllowAppointmentDrag = settings.AllowEdit
					? UsedAppointmentType.Custom
					: UsedAppointmentType.None;
				Scheduler.OptionsCustomization.AllowAppointmentDragBetweenResources = settings.AllowChangeResource
					? UsedAppointmentType.Custom
					: UsedAppointmentType.None;

				Scheduler.OptionsCustomization.AllowAppointmentCreate = UsedAppointmentType.Custom;
	        }
	        catch (Exception)
	        {
				MessageBox.Show("Ein Fehler bei der Darstellung ist aufgetreten.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
	        }
        }

        private void UpdateOptionPanel(AppointmentViewType viewType)
        {
            if (viewType == AppointmentViewType.Day)
            {
                TimelineViewOptions.Visibility = Visibility.Hidden;
                DayViewOptions.Visibility = Visibility.Visible;
                SpinEditDayViewDayCount.Value = Scheduler.DayView.DayCount;
            }
            else if (viewType == AppointmentViewType.Timeline)
            {
                TimelineViewOptions.Visibility = Visibility.Visible;
                DayViewOptions.Visibility = Visibility.Hidden;
                SpinEditTimelineViewDayCount.Value = Scheduler.TimelineView.IntervalCount;
            }
            else
            {
                TimelineViewOptions.Visibility = Visibility.Hidden;
                DayViewOptions.Visibility = Visibility.Hidden;
            }
        }

        private void InitRights()
        {
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_ServiceOverview_View))
            {
            }
        }

        public void ShowView(AppointmentKind kind, int? initialViewType)
        {
            Terminart = kind;
            ViewModel.ActiveViewModelKind = kind;
            Filter1BoxEditLoadFilterOptions();
            if (initialViewType.HasValue)
                Scheduler.ActiveViewType = (SchedulerViewType) initialViewType;
        }

	    private void ButtonDayView_Click(object sender, RoutedEventArgs e)
        {
            Scheduler.ActiveViewType = SchedulerViewType.Day;
            currentViewType = SchedulerViewType.Day;
            ViewModel.SetActiveViewType(currentViewType);
            UpdateOptionPanel(AppointmentViewType.Day);
        }

        private void ButtonWorkWeekView_Click(object sender, RoutedEventArgs e)
        {
            Scheduler.ActiveViewType = SchedulerViewType.WorkWeek;
            currentViewType = SchedulerViewType.WorkWeek;
            ViewModel.SetActiveViewType(currentViewType);
            UpdateOptionPanel(AppointmentViewType.WorkWeek);
        }

        private void ButtonWeekView_Click(object sender, RoutedEventArgs e)
        {
            Scheduler.ActiveViewType = SchedulerViewType.Week;
            currentViewType = SchedulerViewType.Week;
            ViewModel.SetActiveViewType(currentViewType);
            UpdateOptionPanel(AppointmentViewType.Week);
        }

        private void ButtonMonthView_Click(object sender, RoutedEventArgs e)
        {
            Scheduler.ActiveViewType = SchedulerViewType.Month;
            currentViewType = SchedulerViewType.Month;
            ViewModel.SetActiveViewType(currentViewType);
            UpdateOptionPanel(AppointmentViewType.Month);
        }

        private void ButtonTimelineView_Click(object sender, RoutedEventArgs e)
        {
            Scheduler.ActiveViewType = SchedulerViewType.Timeline;
            currentViewType = SchedulerViewType.Timeline;
            ViewModel.SetActiveViewType(currentViewType);
            UpdateOptionPanel(AppointmentViewType.Timeline);
        }

        private void SchedulerStorage_AppointmentsChanged(object sender, PersistentObjectsEventArgs e)
        {
            if (!mIgnoreChangeEvents)
            {
                var appList = e.Objects.Cast<Appointment>().ToList();

                ViewModel.ActiveAppointmentViewModel.SaveAppointments(Scheduler, appList);
            }
        }

        private void SchedulerStorage_AppointmentDeleting(object sender, PersistentObjectCancelEventArgs e)
        {
            var app = e.Object as Appointment;

            if (app != null && app.Type != AppointmentType.ChangedOccurrence)
            {
                String msg = String.Format("Möchten Sie den gewählten Termin wirklich löschen?");
                
                if (app.Type != AppointmentType.DeletedOccurrence &&
                    MessageBox.Show(msg, "BeWoPlaner", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.No)
                {
                    e.Cancel = true;
                }
                else
                {
                    var appList = new List<Appointment>();

                    if (app.Type != AppointmentType.ChangedOccurrence)
                        appList.Add(app);

                    ViewModel.ActiveAppointmentViewModel.DeleteAppointments(Scheduler, appList);
                }
            }
        }

        private void SchedulerStorage_AppointmentsInserted(object sender, PersistentObjectsEventArgs e)
        {
            var appList = e.Objects.Cast<Appointment>().ToList();

            ViewModel.ActiveAppointmentViewModel.InsertNewAppointments(Scheduler, appList);
        }

        private void scheduler_EditAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e)
        {
            var control = sender as SchedulerControl;
            if (control != null)
            {
                var form = ViewModel.GetEditAppointmentForm(control, e.Appointment);
                if (form == null) return;

                e.Form = form;
                e.AllowResize = false;
            }
        }

        private void SchedulerControl_EditRecurrentAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e)
        {
        }

        private void scheduler_PopupMenuShowing(object sender, SchedulerMenuEventArgs e)
        {
            LocalizeMenu(e.Menu);
        }

        private void LocalizeMenu(PopupMenu menu)
        {
            if (menu != null)
            {
                LocalizeItemLinks(menu.ItemLinks);
            }
        }

        private void LocalizeItemLinks(IEnumerable<BarItemLinkBase> links)
        {
            if (links != null)
            {
                foreach (BarItemLinkBase itemlink in links)
                {
                    var lnk = itemlink as BarButtonItemLink;
                    if (lnk != null)
                        LocalizeItem(lnk.Item);
                }
            }
        }

	    private void LocalizeItem(BarItem item)
        {
            if (item != null)
            {
                if (item.Content != null)
                {
                    String content = item.Content.ToString();
                    switch (content)
                    {
                        case "Neuer Termin":
                            if (Terminart.Equals(AppointmentKind.Resource))
                                item.Content = "Neue Buchung";
                            break;
                        case "Neue Terminserie":
                            if (Terminart.Equals(AppointmentKind.Resource))
                                item.Content = "Neue Buchungsserie";
                            break;
                        case "New Appointment":
                            item.Content = Terminart.Equals(AppointmentKind.Resource) ? "Neue Buchung" : "Neuer Termin";
                            break;
                        case "New All Day Event":
                            item.Content = "Neues ganztägiges Ereignis";
                            break;
                        case "New Recurring Appointment":
                            item.Content = Terminart.Equals(AppointmentKind.Resource) ? "Neue Buchungsserie" : "Neue Terminserie";
                            break;
                        case "New Recurring Event":
                            item.Content = "Neue Ereignisserie";
                            break;
                        case "Go to Today":
                            item.Content = "Heute";
                            break;
                        case "Go to Date...":
                            item.Content = "Gehe zu Datum...";
                            break;
                        case "Change View To":
                            item.Content = "Ansicht ändern in";
                            break;
                        case "Day View":
                            item.Content = "Tagesansicht";
                            break;
                        case "Week View":
                            item.Content = "Wochenansicht";
                            break;
                        case "Work Week View":
                            item.Content = "Arbeitswoche";
                            break;
                        case "Month View":
                            item.Content = "Monatsansicht";
                            break;
                        case "Timeline View":
                            item.Content = "Zeitleiste";
                            break;
                        case "Customize Time Ruler...":
                            item.Content = "Maßstab anpassen";
                            break;
                        case "60 Minutes":
                            item.Content = "60 Minuten";
                            break;
                        case "30 Minutes":
                            item.Content = "30 Minuten";
                            break;
                        case "15 Minutes":
                            item.Content = "15 Minuten";
                            break;
                        case "10 Minutes":
                            item.Content = "10 Minuten";
                            break;
                        case "6 Minutes":
                            item.Content = "6 Minuten";
                            break;
                        case "5 Minutes":
                            item.Content = "5 Minuten";
                            break;
                        case "Go to This Day":
                            item.Content = "Gehe zu diesem Tag";
                            break;
                        case "Time Scales":
                            item.Content = "Zeiteinheit";
                            break;
                        case "Month":
                            item.Content = "Monat";
                            break;
                        case "Week":
                            item.Content = "Woche";
                            break;
                        case "Day":
                            item.Content = "Tag";
                            break;
                        case "Hour":
                            item.Content = "Stunde";
                            break;
                        case "Quarter":
                            item.Content = "Quartal";
                            break;
                        case "Year":
                            item.Content = "Jahr";
                            break;
                        case "Time Scale Captions":
                            item.Content = "Zeiteinheit Überschriften";
                            break;
                        case "Open":
                            item.Content = "Öffnen";
                            break;
                        case "Show Time As":
                            item.Content = "Zeigen als";
                            break;
                        case "Free":
                            item.Content = "Frei";
                            break;
                        case "Tentative":
                            item.Content = "Vorläufig";
                            break;
                        case "Busy":
                            item.Content = "Beschäftigt";
                            break;
                        case "Out Of Office":
                            item.Content = "Abwesend";
                            break;
                        case "Label As":
                            item.Content = "Kategorie";
                            break;
                        case "Delete":
                            item.Content = "Löschen";
                            break;
                        case "Edit Series":
                            item.Content = "Serie bearbeiten";
                            break;
                        case "Restore Default State":
                            item.Content = "Auf Serie zurücksetzen";
                            break;
                    }
                }
                if (item is BarSubItem)
                {
                    var subitem = item as BarSubItem;

                    LocalizeItemLinks(subitem.ItemLinks);
                }
            }
        }

        private void scheduler_InitNewAppointment(object sender, AppointmentEventArgs e)
        {
            ViewModel.InitNewAppointment(e.Appointment);
        }

        private void SpinEditDayViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            int count;
            if (e.NewValue != null && Int32.TryParse(e.NewValue.ToString(), out count))
                Scheduler.DayView.DayCount = count;
        }

        private void SpinEditTimelineViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            int count;
            if (e.NewValue != null && Int32.TryParse(e.NewValue.ToString(), out count))
            {
                if (count > 0)
                    Scheduler.TimelineView.IntervalCount = count;
            }
        }

        private void scheduler_AppointmentViewInfoCustomizing(object sender, AppointmentViewInfoCustomizingEventArgs e)
        {
            String customer = String.Empty;

			if (e.ViewInfo.Appointment.ResourceId != null)
			{
				if (Scheduler.Storage.ResourceStorage.DataSource != null)
				{
					var list = Scheduler.Storage.ResourceStorage.DataSource as IList<IBeWoAppointmentResource>;

					if (list != null)
						foreach (IBeWoAppointmentResource item in list)
							if (item.Id.Equals(e.ViewInfo.Appointment.ResourceId))
								customer = item.Caption;
				}
			}
            
            e.ViewInfo.CustomViewInfo = String.Format(e.ViewInfo.AppointmentInterval.Start.Date == e.ViewInfo.AppointmentInterval.End.Date ?
				"{0:HH:mm} - {1:HH:mm} {2}\r\n{3}" :
				"{0:dd.MM HH:mm} - {1:dd.MM HH:mm} {2}\r\n{3}", e.ViewInfo.AppointmentInterval.Start, e.ViewInfo.AppointmentInterval.End, e.ViewInfo.Subject, customer);
        }

	    public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void BeiEigenschaftsAaenderung(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) 
				handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private void SchedulerControl_FilterAppointments(object sender, PersistentObjectCancelEventArgs e)
        {
			if (Filter1BoxEdit.SelectedItem == null || Filter1BoxEdit.SelectedItem.Equals(FilterKein))
			{
				ViewModel.ActiveAppointmentViewModel.SelectedFilterObject = null;
				e.Cancel = false;
				return;
			}

	        switch (Terminart)
	        {
		        case AppointmentKind.CommonCalendar:
			        if (Filter1BoxEdit.SelectedItem.Equals(FilterKlienten))
			        {
				        e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(FilterKlienten, selectedCustomer, (Appointment) e.Object);
				        return;
			        }

				    e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(Filter1BoxEdit.SelectedItem.ToString(), Filter2BoxEdit.SelectedItem, (Appointment)e.Object);
			        break;
				case AppointmentKind.Customer:
					e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(FilterKlienten, selectedCustomer, (Appointment)e.Object);
					return;
				case AppointmentKind.Employee:
					e.Cancel = false;
					break;
				case AppointmentKind.Resource:
					if(Filter1BoxEdit.SelectedItem.Equals(FilterRessourcenkategorien))
					{
						e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(Filter1BoxEdit.SelectedItem.ToString(), selectedResource, (Appointment)e.Object, Scheduler.LimitInterval);
						return;
					}
			        if(Filter1BoxEdit.SelectedItem.Equals(FilterMitarbeiter))
			        {
						e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(Filter1BoxEdit.SelectedItem.ToString(), selectedEmployee, (Appointment)e.Object, Scheduler.LimitInterval);
			        }
					break;
				default:
					e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment(Filter1BoxEdit.SelectedItem.ToString(), Filter2BoxEdit.SelectedItem, (Appointment)e.Object);
			        break;
			}
		}

		private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
	    {
			if (Filter1BoxEdit.SelectedItem != null && Filter1BoxEdit.SelectedItem.Equals(FilterMitarbeiter))
				PopupEmployee.IsOpen = true;
	    }

	    private void EmployeeSearchView_EmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
	    {
			PopupEmployee.IsOpen = false;
			PopupeditEmployee.Focus();

			selectedEmployee = e.Data;

			PopupeditEmployee.Text = selectedEmployee != null ? selectedEmployee.ToString() : string.Empty;

			Scheduler.ActiveView.LayoutChanged();
	    }

	    private void popupedit_customer_PopUpClick(object sender, RoutedEventArgs e)
	    {
		    if (Filter1BoxEdit.SelectedItem != null && Filter1BoxEdit.SelectedItem.Equals(FilterKlienten))
			    PopupCustomer.IsOpen = true;
	    }

	    private void CustomerSearchView_CustomerSelected(object sender, EventArgs<CompactCustomerDC> e)
	    {
			PopupCustomer.IsOpen = false;
		    PopupeditCustomer.Focus();

		    selectedCustomer = e.Data;

			PopupeditCustomer.Text = selectedCustomer != null ? selectedCustomer.ToString() : string.Empty;

			Scheduler.ActiveView.LayoutChanged();
	    }

	    private void ListBoxResources_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
	    {
		    selectedResource = (ResourceDC) ListBoxResources.SelectedItem;
		    if (selectedResource != null)
			    Scheduler.ActiveView.LayoutChanged();
	    }

		private void Filter2BoxEdit_OnSelectedIndexChanged(object sender, RoutedEventArgs e)
	    {
			UpdateListBoxResourcesItemsSource();
	    }

	    private void UpdateListBoxResourcesItemsSource()
	    {
			var x = _AppointmentFilterLists[FilterRessourcen].ToList().Cast<ResourceDC>().ToList();
			ListBoxResources.ItemsSource = x.Where(b => b.ResourceCategory.Equals(Filter2BoxEdit.SelectedItem));
	    }

	    private void AllowAppointmentDragEvent(object sender, AppointmentOperationEventArgs e)
	    {
			if (e.Appointment.CustomFields["KalenderTyp"] == null) return;
			e.Allow = false;
	    }

	    private void AllowAppointmentCreateEvent(object sender, AppointmentOperationEventArgs e)
	    {
		    if (!_Terminart.Equals(AppointmentKind.CommonCalendar)) return;
			e.Allow = false;
	    }

	    private void AllowAppointmentResizeEvent(object sender, AppointmentOperationEventArgs e)
	    {
			if (e.Appointment.CustomFields["KalenderTyp"] == null) return;
			e.Allow = false;
	    }

	    private void AllowAppointmentDragBetweenResourcesEvent(object sender, AppointmentOperationEventArgs e)
	    {
			if (e.Appointment.CustomFields["KalenderTyp"] == null) return;
			e.Allow = false;
	    }

	    private void AllowAppointmentDeleteEvent(object sender, AppointmentOperationEventArgs e)
	    {
			if (e.Appointment.CustomFields["KalenderTyp"] == null) return;
			e.Allow = false;
	    }

		public static readonly DependencyProperty DummyValueProperty = DependencyProperty.Register("DummyValue", typeof(int), typeof(BeWoView), new UIPropertyMetadata(0));

		public int DummyValue
		{
			get { return (int)GetValue(DummyValueProperty); }
			set { SetValue(DummyValueProperty, value); }
		}

		private void Scheduler_OnSelectionlChanged(object sender, EventArgs e)
		{
			var r = new Random();

			var neuerWert = r.Next(0, 1000);
			if (neuerWert == DummyValue)
				neuerWert++;

			DummyValue = neuerWert;
		}

	    private void Scheduler_OnVisibleIntervalChanged(object sender, EventArgs e)
	    {
			var r = new Random();

			var neuerWert = r.Next(0, 1000);
			if (neuerWert == DummyValue)
				neuerWert++;

			DummyValue = neuerWert;
	    }
    }
}