using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

using BeWo.Controls;

namespace BeWo.Core
{
    public class ComboBoxTemplateSelector : DataTemplateSelector
    {
        private readonly Control _Combo;

        public ComboBoxTemplateSelector(Control pCombo)
        {
            this._Combo = pCombo;
            this.SelectedItemTemplate = pCombo.FindResource("SelectedItemTemplate") as DataTemplate;
            this.DropDownItemTemplate = pCombo.FindResource("DropDownItemTemplate") as DataTemplate;
        }

        public DataTemplate DropDownItemTemplate { get; set; }

        public DataTemplate SelectedItemTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item == null)
            {
                return null;
            }

            if (this._Combo is NullItemComboBox && ((NullItemComboBox)this._Combo).NullText.Equals(item))
            {
                return NullItemComboBox.NullTextItemTemplate;
            }

            DependencyObject lParent = container;
            while (!(lParent is ComboBox) && !(lParent is ScrollViewer))
            {
                lParent = VisualTreeHelper.GetParent(lParent);
            }

            return lParent is ComboBox ? this.SelectedItemTemplate : this.DropDownItemTemplate;
        }
    }
}