using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace XLAB
{
    internal sealed class PrfrvdEditWindowViewModel : ObservableObject
    {
        private readonly IReadOnlyList<PrfrvdDirectoryItem> _existingItems;
        private int _activityId;
        private string _validationMessage;

        public PrfrvdEditWindowViewModel(PrfrvdDirectoryItem seed, bool isNew, IReadOnlyList<PrfrvdDirectoryItem> existingItems, PrsnDirectoryService service)
        {
            var source = seed ?? new PrfrvdDirectoryItem();
            _existingItems = existingItems ?? Array.Empty<PrfrvdDirectoryItem>();
            Id = source.Id;
            EmploymentId = source.EmploymentId;
            IsNew = isNew;

            ActivityItems = service.LoadSpvdprReferences();
            ActivityId = source.ActivityId;

            ConfirmCommand = new RelayCommand(Confirm);
            CancelCommand = new RelayCommand(Cancel);
        }

        public event EventHandler<bool?> CloseRequested;

        public int ActivityId
        {
            get { return _activityId; }
            set { SetProperty(ref _activityId, value); }
        }

        public IReadOnlyList<DirectoryLookupItem> ActivityItems { get; private set; }
        public ICommand CancelCommand { get; private set; }
        public ICommand ConfirmCommand { get; private set; }
        public int EmploymentId { get; private set; }
        public int Id { get; private set; }
        public bool IsNew { get; private set; }

        public string Title
        {
            get { return IsNew ? "Новый вид деятельности персоны" : "Редактирование вида деятельности персоны"; }
        }

        public string ValidationMessage
        {
            get { return _validationMessage; }
            private set { SetProperty(ref _validationMessage, value); }
        }

        public PrfrvdDirectoryItem ToResult()
        {
            return new PrfrvdDirectoryItem
            {
                ActivityId = ActivityId,
                EmploymentId = EmploymentId,
                Id = Id
            };
        }

        private void Cancel(object parameter)
        {
            RaiseCloseRequested(false);
        }

        private void Confirm(object parameter)
        {
            if (ActivityId <= 0)
            {
                ValidationMessage = "Укажите вид деятельности персонала.";
                return;
            }

            var duplicate = _existingItems.FirstOrDefault(delegate(PrfrvdDirectoryItem item)
            {
                return item != null
                       && item.Id != Id
                       && item.ActivityId == ActivityId;
            });
            if (duplicate != null)
            {
                ValidationMessage = "Выбранный вид деятельности уже существует у этой записи персонала.";
                return;
            }

            ValidationMessage = string.Empty;
            RaiseCloseRequested(true);
        }

        private void RaiseCloseRequested(bool? dialogResult)
        {
            var handler = CloseRequested;
            if (handler != null)
            {
                handler(this, dialogResult);
            }
        }
    }
}
