using System;

using BS.Shared.Core;

using BeWo.Scheduler.View;
using BeWo.ViewModel;

using DevExpress.XtraScheduler;

namespace BeWo.Scheduler.ViewModel
{
	public class NewSchedulerViewModel
	{
		public event EventHandler<EventArgs<ISchedulerViewModel>> ViewModelChanged;

		private ISchedulerViewModel mActiveAppointmentViewModel;

		public ISchedulerViewModel ActiveAppointmentViewModel
		{
		    get
		    {
		        return mActiveAppointmentViewModel;
		    }

			set
			{
                if ((mActiveAppointmentViewModel == null && value != null) || (mActiveAppointmentViewModel != null && !mActiveAppointmentViewModel.Equals(value)))
			    {
                    mActiveAppointmentViewModel = value;

                    if (ViewModelChanged != null)
                    {
                        ViewModelChanged(this, new EventArgs<ISchedulerViewModel>(value));
                    }
			    }
			}
		}

		public void UpdateAppointmentViewModel(DateTime intervalStart, DateTime intervalEnd)
		{
			VMFactory.CreateNewSchedulerAppointmentListVM(cb =>
			{
				ActiveAppointmentViewModel = cb;
				SchedulerSettings = GetActiveSettings();
				SchedulerSettings.StartDate = intervalStart;
				BeWoApp.MainControl.AufOffeneTerminePruefen();
			}, intervalStart - NewSchedulerView.FetchPadding, intervalEnd + NewSchedulerView.FetchPadding);
		}

		public AbstractAppointmentEditForm GetEditAppointmentForm(DevExpress.Xpf.Scheduler.SchedulerControl control, Appointment appointment)
		{
			return ActiveAppointmentViewModel != null ? ActiveAppointmentViewModel.GetEditAppointmentForm(control, appointment) : null;
		}

		internal void InitNewAppointment(Appointment appointment)
		{
			if (ActiveAppointmentViewModel != null)
			{
			    ActiveAppointmentViewModel.InitNewAppointment(appointment);
			}
		}

		public SchedulerSettings SchedulerSettings { get; set; }

		public SchedulerSettings GetActiveSettings()
		{
			return ActiveAppointmentViewModel == null ? null : SchedulerSettings ?? ActiveAppointmentViewModel.GetDefaultSchedulerSettings();
		}
	}
}
