using System.Collections.Generic;
using System.Windows;

using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;

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

namespace BeWo.View.Detail
{
    public partial class MedRecordEditView
    {
        private MedRecordVM _ViewModel;

        public MedRecordVM ViewModel
        {
            get { return _ViewModel; }
            set { _ViewModel = value; }
        }

        public override bool IsDirty
        {
            get
            {
                return _ViewModel != null && _ViewModel.IsDirty;
            }
        }

        public MedRecordEditView(MedRecordVM pMedRecord)
        {
            InitializeComponent();

            _ViewModel = pMedRecord;

            DataContext = ViewModel;

            PopupeditEmployee.Text = ViewModel.Employee.ToString();

            CustomerSelectionControl.SelectedItem = ViewModel.Customer;
        }

        public bool IsValid()
        {
            return ValidationTrigger.Validate(RootGrid);
        }

        internal override bool DoSaveCheck()
        {
            if (!IsDirty)
            {
                return true;
            }

            var lResult = ShowSaveQuestion();

            if (lResult == MessageBoxResult.Cancel)
            {
                Focus();
                return false;
            }

            if (lResult == MessageBoxResult.Yes)
            {
                SaveData();
            }

            return true;
        }

        protected override void Save()
        {
            if (IsDirty)
            {
                ServiceFacade.DoCustomerServiceSync(s => s.UpdateMedRecords(new List<MedRecordDC> {ViewModel.CommitToDataContract()}));
            }
        }

        private void CustomerSelectionControl_ItemSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            ViewModel.Customer = e.Data;
        }

        private void EmployeeSearchView_ItemSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            PopupEmployee.IsOpen   = false;
            PopupeditEmployee.Text = e.Data.ToString();

            ViewModel.Employee     = e.Data;
        }

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