using Catel;
using Catel.MVVM;
using CatelSample.Common.Base;
using CatelSample.ViewModels.Interfaces;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CatelSample.Views.Base.Controls
{
    public class TabItem : Base_Class, ITabItem
    {
        public TabItem(IViewModel viewModel)
        {
            Argument.IsNotNull(() => viewModel);

            ViewModel = viewModel;
            CanClose = true;

            if (!viewModel.IsClosed)
            {
                viewModel.ClosedAsync += OnViewModelClosed;
            }
        }

        public IViewModel ViewModel { get; private set; }

        public bool CanClose { get; set; }
        public object Tag { get; set; }

        public event EventHandler<EventArgs> Closed;

        private async Task OnViewModelClosed(object sender, ViewModelClosedEventArgs e)
        {
            await Task.Run(() =>
            {
                var vm = ViewModel;

                if (vm != null)
                {
                    vm.ClosedAsync -= OnViewModelClosed;
                }

                Closed.SafeInvoke(this);
            });
        }
    }
}
