using DatabaseEditor.Messages;
using GalaSoft.MvvmLight.CommandWpf;
using PropertyChanged;

namespace DatabaseEditor.ViewModels
{
    [ImplementPropertyChanged]
    public abstract class EditItemViewModel<TDetail, TItem> : ViewModelBase
        where TDetail : new()
    {
        public TDetail ItemDetail { get; set; }

        protected EditItemViewModel()
        {
            ItemDetail = new TDetail();
            MessengerInstance.Register<EditItemMessage<TDetail>>(this, ChangeItem);
            MessengerInstance.Register<AddItemMessage<TItem>>(this, AddItem);
        }

        protected abstract void AddItem(AddItemMessage<TItem> message);

        private void ChangeItem(EditItemMessage<TDetail> message)
        {
            ItemDetail = message.ItemDetail;
        }

        public RelayCommand CancelCommand => new RelayCommand(Cancel);

        public RelayCommand ConfirmCommand => new RelayCommand(Confirm);

        public RelayCommand<TItem> RemoveItemCommand => new RelayCommand<TItem>(RemoveItem);

        protected abstract void RemoveItem(TItem item);

        private void Confirm()
        {
            MessengerInstance.Send(new ConfirmEditMessage<TDetail>(ItemDetail));
        }

        private void Cancel()
        {
            MessengerInstance.Send(new CancelEditMessage());
        }
    }
}