using System.Collections;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace BeWo.Controls
{
    public class NullItemComboBox : ComboBox
    {
        public static readonly DependencyProperty NullTextProperty = DependencyProperty.Register("NullText", typeof(string), typeof(NullItemComboBox), new UIPropertyMetadata(string.Empty));

        private string l;

        public static DataTemplate NullTextItemTemplate
        {
            get
            {
                string lXaml = "<DataTemplate><Label Content=\"{Binding}\" /></DataTemplate>";

                var lParserContext = new ParserContext();
                lParserContext.XmlnsDictionary.Add(string.Empty, "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                lParserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");

                return (DataTemplate)XamlReader.Load(new MemoryStream(Encoding.ASCII.GetBytes(lXaml)), lParserContext);
            }
        }

        public string NullText
        {
            get
            {
                return (string)this.GetValue(NullTextProperty);
            }

            set
            {
                this.SetValue(NullTextProperty, value);
            }
        }

        protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            this.l = this.NullText; // "  ... " + NullText + " ...";
            IEnumerator lEnum = newValue.GetEnumerator();
            if (lEnum.MoveNext() && !lEnum.Current.Equals(this.l))
            {
                ArrayList lTemp = new ArrayList();
                lTemp.Add(this.l);
                do
                {
                    lTemp.Add(lEnum.Current);
                }
                while (lEnum.MoveNext());
                this.ItemsSource = lTemp;
            }
            else
            {
                base.OnItemsSourceChanged(oldValue, newValue);
            }
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            if (this.SelectedItem != null && this.SelectedItem.Equals(this.l))
            {
                this.SelectedIndex = -1;
            }

            base.OnSelectionChanged(e);
        }
    }
}