using DatabaseEditor.BL.Interfaces;
using DatabaseEditor.BL.Models;
using DatabaseEditor.Messages;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Ioc;

namespace DatabaseEditor.ViewModels
{
    public class ItemDetailViewModel<TListModel, TDetail> : ViewModelBase
        where TDetail : TListModel
        where TListModel : ItemModelBase
    {
        private readonly IDetailProvider<TDetail> _detailsProvider;

        public TDetail ItemDetail { get; private set; }

        public ItemDetailViewModel()
        {
            _detailsProvider = SimpleIoc.Default.GetInstance<IDetailProvider<TDetail>>();
            MessengerInstance.Register<ItemSelectedMessage<TListModel>>(this, SelectedItemChanged);
        }

        private void SelectedItemChanged(ItemSelectedMessage<TListModel> message)
        {
            if (message.Item != null)
            {
                ItemDetail = _detailsProvider.GetItemById(message.Item.Id);
            }
            else
            {
                ItemDetail = default(TDetail);
            }
        }

        public RelayCommand<object> ShowRelatedItemCommand => new RelayCommand<object>(ShowRelatedItem);

        public RelayCommand<TDetail> EditCommand => new RelayCommand<TDetail>(EditItem, (d) => (ItemDetail != null));

        public RelayCommand<TDetail> DeleteCommand => new RelayCommand<TDetail>(DeleteItem, (d) => (ItemDetail != null));

        private void DeleteItem(TDetail item)
        {
            MessengerInstance.Send(new DeleteItemMessage<TDetail>(item));
        }

        private void EditItem(TDetail item)
        {
            MessengerInstance.Send(new EditItemMessage<TDetail>(item));
        }

        private void ShowRelatedItem(object item)
        {
            MessengerInstance.Send(new ShowItemMessage(item));
        }
    }
}