using Catel;
using Catel.IoC;
using Catel.MVVM;
using CatelSample.ViewModels.Interfaces;
using CatelSample.Views.Base.Controls;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace CatelSample.Views.Services
{
    public static class ITabServiceExtensions
    {
        public static TabItem Add<TViewModel>(this ITabService tabService, object dataContext = null, bool canClose = false)
            where TViewModel : IViewModel
        {
            Argument.IsNotNull(() => tabService);

            var tabItem = CreateTabItem<TViewModel>(tabService, dataContext);
            tabItem.CanClose = canClose;

            tabService.Add(tabItem);

            return tabItem;
        }

        public static async Task<TabItem> AddAndActivateAsync<TViewModel>(this ITabService tabService, object dataContext = null, bool canClose = false)
            where TViewModel : IViewModel
        {
            await Task.Run(() =>
            {
                Argument.IsNotNull(() => tabService);

                var tabItem = Add<TViewModel>(tabService, dataContext, canClose);
                tabService.Activate(tabItem);

                return tabItem;
            });

            return null;
        }

        public static TabItem CreateTabItem<TViewModel>(this ITabService tabService, object dataContext)
            where TViewModel : IViewModel
        {
            Argument.IsNotNull(() => tabService);

            IViewModel vm;

            if (dataContext != null)
            {
                vm = dataContext as IViewModel;
            }
            else
            {
                var dependencyResolver = tabService.GetDependencyResolver();
                var viewModelFactory = dependencyResolver.Resolve<IViewModelFactory>();
                vm = viewModelFactory.CreateViewModel<TViewModel>(dataContext);
            }

            return new TabItem(vm);
        }

        public static void AddAndActivate(this ITabService tabService, TabItem tabItem)
        {
            Argument.IsNotNull(() => tabService);
            Argument.IsNotNull(() => tabItem);

            tabService.Add(tabItem);
            tabService.Activate(tabItem);
        }

        public static void Clear(this ITabService tabService)
        {
            Argument.IsNotNull(() => tabService);
            tabService.Clear();
        }
    }
}
