using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace SmartAquaViewer.Helper
{
    public static class ComboBoxHelper
    {
        public static readonly DependencyProperty SelectFirstOnItemsChangeProperty =
            DependencyProperty.RegisterAttached(
                "SelectFirstOnItemsChange", typeof(bool), typeof(ComboBoxHelper),
                new PropertyMetadata(false, OnSelectFirstChanged));

        public static void SetSelectFirstOnItemsChange(DependencyObject obj, bool value)
            => obj.SetValue(SelectFirstOnItemsChangeProperty, value);
        public static bool GetSelectFirstOnItemsChange(DependencyObject obj)
            => (bool)obj.GetValue(SelectFirstOnItemsChangeProperty);

        private static void OnSelectFirstChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not ComboBox cb) return;

            void TrySelectFirst()
            {
                if (cb.Items.Count > 0 && cb.SelectedIndex < 0)
                    cb.SelectedIndex = 0;
            }

            cb.Loaded += (_, __) => TrySelectFirst();

            void Hook()
            {
                if (cb.ItemsSource is INotifyCollectionChanged incc)
                {
                    incc.CollectionChanged -= OnItemsChanged;
                    incc.CollectionChanged += OnItemsChanged;
                }
            }
            void OnItemsChanged(object? s, NotifyCollectionChangedEventArgs args) => TrySelectFirst();

            // ItemsSource가 바뀌어도 다시 훅
            cb.DataContextChanged += (_, __) => Hook();
            Hook();
        }
    }
}
