using Catel.MVVM;
using Catel.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CatelSample.Views.Base.Controls
{
    /// <summary>
    /// Interaction logic for ClosableTabItem.xaml
    /// </summary>
    public partial class ClosableTabItem : UserControl
    {
        public ClosableTabItem()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string),
            typeof(ClosableTabItem), new PropertyMetadata(string.Empty));


        public bool CanClose
        {
            get { return (bool)GetValue(CanCloseProperty); }
            set { SetValue(CanCloseProperty, value); }
        }

        public static readonly DependencyProperty CanCloseProperty = DependencyProperty.Register("CanClose", typeof(bool),
            typeof(ClosableTabItem), new PropertyMetadata(true));

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            var vmContainer = Content as IViewModelContainer;

            if (vmContainer == null)
            {
                return;
            }

            var vm = vmContainer.ViewModel;

            if (vm == null)
            {
                var frameworkElement = vmContainer as FrameworkElement;

                if (frameworkElement != null)
                {
                    vm = frameworkElement.DataContext as IViewModel;
                }

                if (vm == null)
                {
                    return;
                }
            }

            SetBinding(TitleProperty, new Binding
            {
                Source = vm,
                Path = new PropertyPath("Title")
            });
        }

        private void OnCloseButtonClick(object sender, RoutedEventArgs e)
        {
            if (!CanClose)
            {
                return;
            }

            var tabControl = this.FindVisualAncestorByType<TabControl>();

            if (tabControl != null)
            {
                tabControl.RemoveAndUpdateSelection(DataContext);
            }
        }
    }
}
