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

namespace XLAB
{
    internal sealed class SpnmtpEditWindowViewModel : ObservableObject
    {
        private readonly IReadOnlyList<SpnmtpDirectoryItem> _existingItems;
        private string _name;
        private string _specialName;
        private string _validationMessage;

        public SpnmtpEditWindowViewModel(SpnmtpDirectoryItem seed, bool isNew, IReadOnlyList<SpnmtpDirectoryItem> existingItems)
        {
            var source = seed ?? new SpnmtpDirectoryItem();
            _existingItems = existingItems ?? Array.Empty<SpnmtpDirectoryItem>();
            Id = source.Id;
            IsNew = isNew;
            Name = source.Name ?? string.Empty;
            SpecialName = source.SpecialName ?? string.Empty;

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

        public event EventHandler<bool?> CloseRequested;

        public ICommand CancelCommand { get; private set; }

        public ICommand ConfirmCommand { get; private set; }

        public int Id { get; private set; }

        public bool IsNew { get; private set; }

        public string Name
        {
            get { return _name; }
            set { SetProperty(ref _name, value); }
        }

        public string SpecialName
        {
            get { return _specialName; }
            set { SetProperty(ref _specialName, value); }
        }

        public string Title
        {
            get { return IsNew ? "Новое наименование типа СИ" : "Редактирование наименования типа СИ"; }
        }

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

        public SpnmtpDirectoryItem ToResult()
        {
            return new SpnmtpDirectoryItem
            {
                Id = Id,
                Name = string.IsNullOrWhiteSpace(Name) ? string.Empty : Name.Trim(),
                SpecialName = string.IsNullOrWhiteSpace(SpecialName) ? string.Empty : SpecialName.Trim()
            };
        }

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

        private void Confirm(object parameter)
        {
            var normalizedName = string.IsNullOrWhiteSpace(Name) ? string.Empty : Name.Trim();
            var normalizedSpecialName = string.IsNullOrWhiteSpace(SpecialName) ? string.Empty : SpecialName.Trim();

            if (normalizedName.Length == 0)
            {
                ValidationMessage = "Укажите наименование типа СИ.";
                return;
            }

            if (normalizedName.Length > SpnmtpDirectoryRules.NameMaxLength)
            {
                ValidationMessage = string.Format("Наименование типа СИ не должно превышать {0} символов.", SpnmtpDirectoryRules.NameMaxLength);
                return;
            }

            if (normalizedSpecialName.Length > SpnmtpDirectoryRules.SpecialNameMaxLength)
            {
                ValidationMessage = string.Format("Специальное наименование типа не должно превышать {0} символов.", SpnmtpDirectoryRules.SpecialNameMaxLength);
                return;
            }

            var duplicate = _existingItems.FirstOrDefault(delegate(SpnmtpDirectoryItem item)
            {
                return item != null
                       && item.Id != Id
                       && string.Equals(
                           string.IsNullOrWhiteSpace(item.Name) ? string.Empty : item.Name.Trim(),
                           normalizedName,
                           StringComparison.OrdinalIgnoreCase);
            });
            if (duplicate != null)
            {
                ValidationMessage = string.Format("Наименование типа СИ \"{0}\" уже существует в справочнике.", normalizedName);
                return;
            }

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

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