using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Brush = System.Windows.Media.Brush;
using Brushes = System.Windows.Media.Brushes;

namespace Elwig.Helpers {
    public class ControlUtils {

        public enum RenewSourceDefault {
            None,
            IfOnly,
            First
        }

        private static void SetControlBorderBrush(Control input, Brush brush) {
            if (input is ComboBox cb) {
                var border = GetComboBoxBorder(cb);
                if (border != null) border.BorderBrush = brush;
            } else {
                input.BorderBrush = brush;
            }
        }

        public static void SetInputNotDefault(Control input) {
            SetControlBorderBrush(input, Brushes.Gold);
        }

        public static void SetInputChanged(Control input) {
            SetControlBorderBrush(input, Brushes.Orange);
        }

        public static void SetInputInvalid(Control input) {
            SetControlBorderBrush(input, Brushes.Red);
        }

        public static void ClearInputState(Control input) {
            if (input is ComboBox cb) {
                GetComboBoxBorder(cb)?.ClearValue(Border.BorderBrushProperty);
            } else {
                input.ClearValue(Control.BorderBrushProperty);
            }
        }

        private static Border? GetComboBoxBorder(ComboBox cb) {
            var toggleButton = cb.Template.FindName("toggleButton", cb) as ToggleButton;
            return toggleButton?.Template.FindName("templateRoot", toggleButton) as Border;
        }

        public static IEnumerable<T> FindAllChildren<T>(DependencyObject depObj) where T : DependencyObject {
            if (depObj == null)
                yield return (T)Enumerable.Empty<T>();
            foreach (var child in LogicalTreeHelper.GetChildren(depObj)) {
                if (child == null) {
                    continue;
                } else if (child is T t) {
                    yield return t;
                }
                if (child is DependencyObject childDepOpj) {
                    foreach (T childOfChild in FindAllChildren<T>(childDepOpj)) {
                        yield return childOfChild;
                    }
                }
            }
        }

        public static IEnumerable<T> FindAllChildren<T>(DependencyObject depObj, IEnumerable<DependencyObject> exempt) where T : DependencyObject {
            return FindAllChildren<T>(depObj).Where(c => !exempt.Contains(c));
        }

        public static T? FindNextSibling<T>(Control me) where T : DependencyObject {
            var found = false;
            foreach (var child in LogicalTreeHelper.GetChildren(me.Parent)) {
                if (found && child is T c) {
                    return c;
                } else if (child == me) {
                    found = true;
                }
            }
            return null;
        }

        public static void RenewItemsSource(Selector selector, IEnumerable? source, Func<object?, object?> getId, SelectionChangedEventHandler? handler = null, RenewSourceDefault def = RenewSourceDefault.None) {
            if (selector.ItemsSource == source)
                return;
            var selectedId = getId(selector.SelectedItem);
            object? selItem = null;
            if (selectedId != null && source != null)
                selItem = source.Cast<object>().FirstOrDefault(i => selectedId.Equals(getId(i)));
            if (source != null && selItem == null) {
                if ((def == RenewSourceDefault.IfOnly && source.Cast<object>().Count() == 1) || def == RenewSourceDefault.First) {
                    selItem = source.Cast<object>().First();
                }
            }
            if (handler != null && selItem != null) selector.SelectionChanged -= handler;
            selector.ItemsSource = source;
            if (handler != null && selItem != null) selector.SelectionChanged += handler;
            selector.SelectedItem = selItem;
        }

        public static void RenewItemsSource(Xceed.Wpf.Toolkit.Primitives.Selector selector, IEnumerable? source, Func<object?, object?> getId) {
            if (selector.ItemsSource == source)
                return;
            var selectedIds = selector.SelectedItems.Cast<object>().Select(i => getId(i)).ToList();
            selector.ItemsSource = source;
            if (source != null) {
                selector.SelectedItems.Clear();
                foreach (var i in source.Cast<object>().Where(i => selectedIds.Contains(getId(i))))
                    selector.SelectedItems.Add(i);
            }
        }

        public static void RenewItemsSource(DataGrid dataGrid, IEnumerable? source, Func<object?, object?> getId, SelectionChangedEventHandler? handler = null, RenewSourceDefault def = RenewSourceDefault.None, bool keepSort = true) {
            if (dataGrid.ItemsSource == source)
                return;
            var column = dataGrid.CurrentCell.Column;
            var sortColumns = dataGrid.Columns.Select(c => c.SortDirection).ToList();
            var sort = dataGrid.Items.SortDescriptions.ToList();
            var selectedId = getId(dataGrid.SelectedItem);
            object? selItem = null;
            if (selectedId != null && source != null)
                selItem = source.Cast<object>().FirstOrDefault(i => selectedId.Equals(getId(i)));
            if (source != null && selItem == null) {
                if ((def == RenewSourceDefault.IfOnly && source.Cast<object>().Count() == 1) || def == RenewSourceDefault.First) {
                    selItem = source.Cast<object>().First();
                }
            }
            if (handler != null && selItem != null) dataGrid.SelectionChanged -= handler;
            dataGrid.ItemsSource = source;
            if (handler != null && selItem != null) dataGrid.SelectionChanged += handler;
            dataGrid.SelectedItem = selItem;
            if (keepSort) {
                for (int i = 0; i < dataGrid.Columns.Count; i++)
                    dataGrid.Columns[i].SortDirection = sortColumns[i];
                foreach (var s in sort)
                    dataGrid.Items.SortDescriptions.Add(s);
            }
            if (dataGrid.SelectedItem != null && column != null)
                dataGrid.CurrentCell = new(dataGrid.SelectedItem, column);
        }

        public static void RenewItemsSource(ListBox listBox, IEnumerable? source, Func<object?, object?> getId, SelectionChangedEventHandler? handler = null, RenewSourceDefault def = RenewSourceDefault.None) {
            if (listBox.ItemsSource == source)
                return;
            var selectedId = getId(listBox.SelectedItem);
            object? selItem = null;
            if (selectedId != null && source != null)
                selItem = source.Cast<object>().FirstOrDefault(i => selectedId.Equals(getId(i)));
            if (source != null && selItem == null) {
                if ((def == RenewSourceDefault.IfOnly && source.Cast<object>().Count() == 1) || def == RenewSourceDefault.First) {
                    selItem = source.Cast<object>().FirstOrDefault();
                }
            }
            if (handler != null && selItem != null) listBox.SelectionChanged -= handler;
            listBox.ItemsSource = source;
            if (handler != null && selItem != null) listBox.SelectionChanged += handler;
            listBox.SelectedItem = selItem;
        }

        public static object? GetItemFromSource(IEnumerable source, Func<object?, object?> getId, object? id) {
            if (source == null)
                return null;
            var items = source.Cast<object>();
            var item = items.Where(i => getId(i)?.Equals(id) ?? false).FirstOrDefault();
            if (item == null && items.Any(i => i is NullItem))
                return items.Where(i => i is NullItem).First();
            return item;
        }

        public static object? GetItemFromSource(IEnumerable source, object? item, Func<object?, object?> getId) {
            return GetItemFromSource(source, getId, getId(item));
        }

        public static void SelectComboBoxItem(ComboBox cb, Func<object?, object?> getId, object? id) {
            cb.SelectedItem = GetItemFromSource(cb.ItemsSource, getId, id);
        }

        public static void SelectComboBoxItem(ComboBox cb, object? item, Func<object?, object?> getId) {
            SelectComboBoxItem(cb, getId, getId(item));
        }

        public static void SelectListBoxItem(ListBox lb, Func<object?, object?> getId, object? id) {
            lb.SelectedItem = GetItemFromSource(lb.ItemsSource, getId, id);
            lb.ScrollIntoView(lb.SelectedItem);
        }

        public static void SelectListBoxItem(ListBox lb, object? item, Func<object?, object?> getId) {
            SelectListBoxItem(lb, getId, getId(item));
        }

        public static IEnumerable<object?> GetItemsFromSource(IEnumerable source, Func<object?, object?> getId, IEnumerable<object?> ids) {
            if (source == null)
                return Array.Empty<object>();
            return source.Cast<object>().Where(i => ids.Any(c => c?.Equals(getId(i)) ?? false));
        }

        public static IEnumerable<object?> GetItemsFromSource(IEnumerable source, IEnumerable<object?>? items, Func<object?, object?> getId) {
            if (items == null)
                return Array.Empty<object>();
            return GetItemsFromSource(source, getId, items.Select(i => getId(i)));
        }

        public static void SelectCheckComboBoxItems(Xceed.Wpf.Toolkit.CheckComboBox ccb, Func<object?, object?> getId, IEnumerable<object?>? ids) {
            ccb.SelectedItems.Clear();
            if (ids == null) return;
            foreach (var id in ids)
                ccb.SelectedItems.Add(GetItemFromSource(ccb.ItemsSource, getId, id));
        }

        public static void SelectCheckComboBoxItems(Xceed.Wpf.Toolkit.CheckComboBox ccb, IEnumerable<object>? items, Func<object?, object?> getId) {
            SelectCheckComboBoxItems(ccb, getId, items?.Select(i => getId(i)));
        }

        public static object? GetInputValue(Control input) {
            if (input is TextBox tb) {
                return tb.Text;
            } else if (input is ComboBox sb) {
                return sb.SelectedItem;
            } else if (input is Xceed.Wpf.Toolkit.CheckComboBox ccb) {
                return ccb.SelectedItems.Cast<object>().ToArray();
            } else if (input is CheckBox cb) {
                return cb.IsChecked?.ToString();
            } else if (input is RadioButton rb) {
                return rb.IsChecked?.ToString();
            } else {
                return null;
            }
        }
    }
}
