using MaxwellFramework.Core.Common.Command;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MainShell.Recipe.ViewModel
{
    public class RecipeReNameWindowModel : PropertyChangedBase
    {
        private bool? _dialogResult;
        public bool? DialogResult
        {
            get => _dialogResult;
            set => SetAndNotify(ref _dialogResult, value);
        }

        private string _recipeName;
        public string RecipeName
        {
            get => _recipeName;
            set
            {
                if (SetAndNotify(ref _recipeName, value))
                {
                    UpdateValidationMessage();
                    ((DelegateCommand)OkCommand).RaiseCanExecuteChanged();
                }
            }
        }
        private string _oldRecipeName;

        public string OldRecipeName
        {
            get { return _oldRecipeName; }
            set { SetAndNotify(ref _oldRecipeName, value); } 
        }

        private string _validationMessage;
        /// <summary>
        /// 在界面上显示的验证信息（为空时不显示）
        /// </summary>
        public string ValidationMessage
        {
            get => _validationMessage;
            set => SetAndNotify(ref _validationMessage, value);
        }

        public IEnumerable<string> ExistingRecipeNames { get; set; }
        public ICommand OkCommand { get; }
        public ICommand CancelCommand { get; }
        public RecipeReNameWindowModel()
        {
            OkCommand = new DelegateCommand(OnOk, CanOk);
            CancelCommand = new DelegateCommand(OnCancel);
        }
        private void OnOk(object obj)
        {
            DialogResult = true;
        }
        private bool CanOk(object obj)
        {
            if (string.IsNullOrWhiteSpace(RecipeName))
                return false;
            if (ExistingRecipeNames != null && ExistingRecipeNames.Contains(RecipeName, StringComparer.OrdinalIgnoreCase))
                return false;
            return true;
        }
        private void OnCancel(object obj)
        {
            DialogResult = false;
        }
        private void UpdateValidationMessage()
        {
            if (string.IsNullOrWhiteSpace(RecipeName))
            {
                ValidationMessage = "名称不能为空";
                return;
            }

            if (ExistingRecipeNames != null && ExistingRecipeNames.Contains(RecipeName, StringComparer.OrdinalIgnoreCase))
            {
                ValidationMessage = "名称已存在";
                return;
            }

            ValidationMessage = string.Empty;
        }
    }
}
