using SelectedItemsBinding;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Telerik.Windows.Controls;

namespace SelectedItemsBinding
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
    {
        private string textCache;

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new AgencyViewModel();
        }

        private void RadComboBox_PreviewLostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            this.textCache = this.radComboBox.Text;
        }
        private void RadComboBox_LostFocus(object sender, RoutedEventArgs e)
        {
            this.radComboBox.GetType().GetMethod("UpdateText", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(this.radComboBox, new object[] { textCache, true });
        }

        private void radComboBox_GotFocus(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                this.radComboBox.GetType().GetMethod("UpdateText", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(this.radComboBox, new object[] { textCache, true });
            }), DispatcherPriority.Loaded);
        }
    }

    public class CustomFilteringBehavior : ComboBoxFilteringBehavior
    {
        public override int FindFullMatchIndex(ReadOnlyCollection<int> matchIndexes)
        {
            var index = base.FindFullMatchIndex(matchIndexes);
            return index;
        }

        public override List<int> FindMatchingIndexes(string text)
        {
            var indexes = base.FindMatchingIndexes(text);
            
            if (!string.IsNullOrEmpty(text) && indexes.Count == 0)
            {
                indexes.AddRange(Enumerable.Range(0, this.ComboBox.Items.Count));
            }

            return indexes;
        }
    }
}
