using System;
using System.Windows.Input;

namespace XLAB
{
    internal sealed class CreateDocumentWindowViewModel : ObservableObject
    {
        private DateTime? _acceptedOn;
        private string _documentNumber;
        private string _validationMessage;

        public CreateDocumentWindowViewModel(DocumentEditorResult seed)
        {
            _acceptedOn = seed != null ? seed.AcceptedOn : DateTime.Today;
            _documentNumber = seed != null ? seed.DocumentNumber : string.Empty;

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

        public event EventHandler<bool?> CloseRequested;

        public DateTime? AcceptedOn
        {
            get { return _acceptedOn; }
            set { SetProperty(ref _acceptedOn, value); }
        }

        public ICommand CancelCommand { get; private set; }

        public ICommand ConfirmCommand { get; private set; }

        public string DocumentNumber
        {
            get { return _documentNumber; }
            set { SetProperty(ref _documentNumber, value); }
        }

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

        public DocumentEditorResult ToResult()
        {
            return new DocumentEditorResult
            {
                DocumentNumber = DocumentNumber == null ? string.Empty : DocumentNumber.Trim(),
                AcceptedOn = AcceptedOn.HasValue ? AcceptedOn.Value : DateTime.Today,
                IssuedOn = null
            };
        }

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

        private void Confirm(object parameter)
        {
            if (string.IsNullOrWhiteSpace(DocumentNumber))
            {
                ValidationMessage = "Введите номер ПСВ.";
                return;
            }

            if (!AcceptedOn.HasValue)
            {
                ValidationMessage = "Укажите дату приемки.";
                return;
            }

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

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