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

namespace XLAB2
{
    internal sealed class FrpdvdEditWindowViewModel : ObservableObject
    {
        private readonly IReadOnlyList<FrpdvdDirectoryItem> _existingItems;
        private int _activityId;
        private string _validationMessage;

        public FrpdvdEditWindowViewModel(FrpdvdDirectoryItem seed, bool isNew, IReadOnlyList<FrpdvdDirectoryItem> existingItems, FrpdDirectoryService service)
        {
            var source = seed ?? new FrpdvdDirectoryItem();
            _existingItems = existingItems ?? Array.Empty<FrpdvdDirectoryItem>();
            Id = source.Id;
            FrpdId = source.FrpdId;
            IsNew = isNew;

            ActivityItems = service.LoadSpvddoReferences();
            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 FrpdId { 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 FrpdvdDirectoryItem ToResult()
        {
            return new FrpdvdDirectoryItem
            {
                ActivityId = ActivityId,
                FrpdId = FrpdId,
                Id = Id
            };
        }

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

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

            var duplicate = _existingItems.FirstOrDefault(delegate(FrpdvdDirectoryItem 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);
            }
        }
    }
}
