using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using BeWo.Scheduler.ViewModel;
using DevExpress.Xpf.Scheduler.UI;
using DevExpress.Xpf.Scheduler;
using DevExpress.XtraScheduler;

using BS.Shared.DataContracts.Compact;
using BS.Shared.Core;


namespace BeWo.Scheduler.View
{
    public partial class CustomerAppointmentEditForm
    {
        private readonly IList<CompactCustomerDC> mCustomerList;
        private readonly IList<CompactEmployeeDC> mEmployeeList;

        public CustomerAppointmentEditForm() 
        {
            InitializeComponent();
        }

		public AppointmentListVM ViewModel { get; set; }

        public CustomerAppointmentEditForm(AppointmentListVM vm, SchedulerControl schedulerControl,
            Appointment appointment, IList<CompactCustomerDC> customers, IList<CompactEmployeeDC> employees, object selectedFilterObject)
            : base(schedulerControl, appointment)
        {
	        ViewModel = vm;
            mCustomerList = customers;
            mEmployeeList = employees;
            InitializeComponent();

            LblRecurrenceType.Visibility = ShouldShowRecurrence ? Visibility.Visible : Visibility.Collapsed;
            EdtRecurrenceType.Visibility = ShouldShowRecurrence ? Visibility.Visible : Visibility.Collapsed;
	        
            EdtRecurrenceType.CustomDisplayText += edtRecurrenceType_CustomDisplayText;

            LabelEdit.ItemsSource = Controller.Storage.AppointmentStorage.Labels;
            LabelEdit.EditValue = Controller.Label;

	        var filterObject = selectedFilterObject as CompactCustomerDC;
	        if(filterObject != null)
				CustomerController.ResourceId = filterObject.CustomerOid;

            InitCombos();
            
            MonthlyRecurrenceControl.Loaded += recurrenceControl_Loaded;
            YearlyRecurrenceControl.Loaded += recurrenceControl_Loaded;
        }

        static void recurrenceControl_Loaded(object sender, RoutedEventArgs e)
        {
            LocalizeVisualChild(sender as DependencyObject);
        }

        public override AppointmentFormController CreateFormController(SchedulerControl schedulerControl, Appointment appointment)
        {
            return new CustomerAppointmentFormController(schedulerControl, appointment);
        }

        public CustomerAppointmentFormController CustomerController { get { return Controller as CustomerAppointmentFormController; } }

        private void InitCombos()
        {
            long? customerOid = null;

            if (Controller.ResourceId != null && Controller.ResourceId != Resource.Empty)
                customerOid = (long) Controller.ResourceId;
	        customerOid = CustomerController.CustomerOid;

            var employeeOid = CustomerController.EmployeeOid;
            if (!employeeOid.HasValue)
                employeeOid = BeWoApp.LoggedOnEmployee.EmployeeOid;

            CompactCustomerDC customer = null;

            if (mCustomerList != null)
                foreach (var item in mCustomerList)
                    if (item.CustomerOid == customerOid)
                        customer = item;
            
            CompactEmployeeDC employee = null;

            if (mEmployeeList != null)
            foreach (var item in mEmployeeList.Where(item => item.EmployeeOid == employeeOid))
                    employee = item;
            
            if (customer != null)
                PopupeditCustomer.Text = customer.ToString();

            if (employee != null)
                PopupeditEmployee.Text = employee.ToString();
        }

        static void edtRecurrenceType_CustomDisplayText(object sender, DevExpress.Xpf.Editors.CustomDisplayTextEventArgs e)
        {
            var conv = new Converter.Recurrence2GermanConverter();

            e.DisplayText = (String)conv.Convert(e.EditValue, typeof(String), null, null);
            e.Handled = true;
        }

        public IList<CompactCustomerDC> CustomerList { get { return mCustomerList; } }

        public IList<CompactEmployeeDC> EmployeeList { get { return mEmployeeList; } }
        
        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
			var empOid = CustomerController.EmployeeOid;

			if (Appointment.RecurrenceInfo != null)
				ViewModel.ApplyChangesToChangedOccurencyCustomFields(empOid.Value, CustomerController.CustomerOid.Value, Appointment.RecurrenceIndex.ToString(), Appointment.RecurrenceInfo.Id);

            ApplyChanges();
        }
        
        private void button_cancel_Click(object sender, RoutedEventArgs e)
        {
            Cancel();
        }

        private void button_delete_Click(object sender, RoutedEventArgs e)
        {
            DeleteAppointment();
        }

        private void popupedit_customer_PopUpClick(object sender, RoutedEventArgs e)
        {
            PopupCustomer.IsOpen = true;
        }

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

            var customer = e.Data;

            if (customer != null)
            {
                if (customer.Oid != null)
                {
	                Controller.ResourceId = customer.Oid.Value;
	                CustomerController.CustomerOid = customer.Oid;
                }
                PopupeditCustomer.Text = customer.ToString();
            }
            else
            {
                PopupeditCustomer.Text = String.Empty;
            }
        }

        private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            PopupEmployee.IsOpen = true;
        }

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

            var emp = e.Data;

            if (emp != null)
            {
                CustomerController.EmployeeOid = emp.EmployeeOid;
                PopupeditEmployee.Text = emp.ToString();
            }
            else
            {
                PopupeditEmployee.Text = String.Empty;
            }
        }


        private void edtRecurrenceType_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            var te = e.NewValue as RecurrenceTypeElement;
            //if (te != null && te.RecurrenceType.HasValue)
            //{
            //    this.Height = 570;
            //    this.ParentLayoutInvalidated(this);
            //}
            //else
            //{
            //    this.Height = 270;
            //}
        }

        private void labelEdit_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            Controller.Label = e.NewValue as AppointmentLabel;
        }
    }

    public class CustomerAppointmentFormController : AppointmentFormController
    {
        public long? EmployeeOid
        {
            get
            {
                return (long?) EditedAppointmentCopy.CustomFields["EmployeeOid"];
            }
            set
            {
                EditedAppointmentCopy.CustomFields["EmployeeOid"] = value;
            }
        }

		public long? CustomerOid
		{
			get
			{
				return (long?)EditedAppointmentCopy.CustomFields["CustomerOid"];
			}
			set
			{
				EditedAppointmentCopy.CustomFields["CustomerOid"] = value;
			}
		}

        private long? SourceEmployeeOid
        {
            get
            {
                return (long?) SourceAppointment.CustomFields["EmployeeOid"];
            }
            set
            {
                SourceAppointment.CustomFields["EmployeeOid"] = value;
            }
        }

		private long? SourceCustomerOid
		{
			get
			{
				return (long?)SourceAppointment.CustomFields["CustomerOid"];
			}
			set
			{
				SourceAppointment.CustomFields["CustomerOid"] = value;
			}
		}

        public CustomerAppointmentFormController(SchedulerControl control, Appointment apt) : base(control, apt)
        {
        }

        public override bool IsAppointmentChanged()
        {
            if (base.IsAppointmentChanged())
                return true;


            if (!SourceEmployeeOid.HasValue && !EmployeeOid.HasValue)
                return false;

			if (!SourceCustomerOid.HasValue && !CustomerOid.HasValue)
				return false;

			return !SourceEmployeeOid.HasValue || !EmployeeOid.HasValue || SourceEmployeeOid != EmployeeOid || !SourceCustomerOid.HasValue || !CustomerOid.HasValue || SourceCustomerOid != CustomerOid;
        }

        protected override void ApplyCustomFieldsValues()
        {
            SourceEmployeeOid = EmployeeOid;
        }
    }   
}
