using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using CustomDockingPanesFactory.ViewModels;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Docking;

namespace CustomDockingPanesFactory
{
    public class MyDockingPanesFactory : DockingPanesFactory
    {
	    protected override RadPane CreatePaneForItem(object item)
	    {
		    var viewModel = item as IPaneViewModel;
		    if (viewModel != null)
		    {
			    RadPane radPane = viewModel.IsDocument ? new RadDocumentPane() : new RadPane();
			    radPane.DataContext = item;
			    radPane.Header = viewModel.Header;
			    radPane.Tag = viewModel.DockingPosition.ToString();
			    radPane.CanUserClose = viewModel.IsDocument;

			    RadDocking.SetSerializationTag(radPane, viewModel.Header);
			    UIElement shellView = ViewLocator.Locate(viewModel);
			    radPane.Content = shellView;

				return radPane;
		    }
		    return base.CreatePaneForItem(item);
	    }
        protected override void AddPane(Telerik.Windows.Controls.RadDocking radDocking, Telerik.Windows.Controls.RadPane pane)
        {
            var tag = pane.Tag.ToString();
            var paneGroup = radDocking.SplitItems.ToList().FirstOrDefault(i => i.Control.Name.Contains(tag)) as RadPaneGroup;

            if (paneGroup != null)
            {
	            int i = paneGroup.Items.Count;
	            pane.Header += " " + (i+1).ToString();
                paneGroup.Items.Add(pane);
            }
            else
            {
                base.AddPane(radDocking, pane);
            }
        }
    }
}
