using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using BeWo.View;
using DevExpress.Xpf.Grid;


namespace BeWo.Core
{
    public class BeWoWpfUtils
    {
        public static readonly DependencyProperty AutoHeightRowCountProperty = DependencyProperty.RegisterAttached(
            "AutoHeightRowCount", 
            typeof(Int32), 
            typeof(BeWoWpfUtils), 
            new FrameworkPropertyMetadata(
                1, 
                FrameworkPropertyMetadataOptions.AffectsRender, 
                (s, e) =>
                    {
                        if (s is Grid)
                        {
                            Grid grid = s as Grid;
                            grid.RowDefinitions.Clear();
                            for (int i = 0; i < 30; i++)
                            {
                                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                            }
                        }
                    }));

        public static readonly DependencyProperty AutoWidthColumnCountProperty = DependencyProperty.RegisterAttached(
            "AutoWidthColumnCount", 
            typeof(Int32), 
            typeof(BeWoWpfUtils), 
            new FrameworkPropertyMetadata(
                1, 
                FrameworkPropertyMetadataOptions.AffectsRender, 
                (s, e) =>
                    {
                        if (s is Grid)
                        {
                            Grid grid = s as Grid;
                            grid.ColumnDefinitions.Clear();
                            for (int i = 0; i < 30; i++)
                            {
                                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
                            }
                        }
                    }));

        public static readonly DependencyProperty IsExpanderButtonVisibleProperty = DependencyProperty.RegisterAttached("IsExpanderButtonVisible", typeof(Boolean), typeof(BeWoWpfUtils), new FrameworkPropertyMetadata(true));

        public static readonly DependencyProperty SelectedItemsListProperty = DependencyProperty.RegisterAttached(
            "SelectedItemsList", 
            typeof(List<string>), 
            typeof(BeWoWpfUtils), 
            new FrameworkPropertyMetadata(
                new List<string>(), 
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
                (s, e) =>
                    {
                        var d = e.NewValue as List<string>;
                        var c = s as ListBox;
                        c.SelectionChanged -= c_SelectionChanged;
                        c.SelectedItems.Clear();
                        if (d != null)
                        {
                            d.ForEach(i => c.SelectedItems.Add(i));
                        }

                        c.SelectionChanged += c_SelectionChanged;
                    }));

        public static int GetAutoHeightRowCount(UIElement element)
        {
            return (int)element.GetValue(AutoHeightRowCountProperty);
        }

        public static int GetAutoWidthColumnCount(UIElement element)
        {
            return (int)element.GetValue(AutoWidthColumnCountProperty);
        }

        public static string GetHTMLEncodedURL(string url)
        {
            // string newurl = url.Replace("ä", "%c3%a4")
            // .Replace("ö", "%c3%b6")
            // .Replace("ü", "%c3%bc")
            // .Replace("Ä", "%c3%84")
            // .Replace("Ö", "%c3%96")
            // .Replace("Ü", "%c3%9c")
            // .Replace("ß", "%c3%9f");
            return url;
        }

        public static bool GetIsExpanderButtonVisible(UIElement element)
        {
            return (Boolean)element.GetValue(IsExpanderButtonVisibleProperty);
        }

        public static IEnumerable<string> GetSelectedItemsList(UIElement element)
        {
            return (List<string>)element.GetValue(SelectedItemsListProperty);
        }

        public static T GetTag<T>(object control)
        {
            return (T)((Control)control).Tag;
        }

        public static void RefreshDXGrid(GridControl gridcontrol)
        {
            var lView = gridcontrol.View;
            var lData = lView.FocusedRowData;

            var count = 0;

            var col = gridcontrol.ItemsSource as ICollection;
            if (col != null)
            {
                count = col.Count;
            }
            else
            {
                var list = gridcontrol.DataSource as IList;
                if (list != null)
                    count = list.Count;
            }

            if (lData.RowHandle.Value + 1 > count)
                gridcontrol.RefreshData();
        }

        public static void SetAutoHeightRowCount(UIElement element, int value)
        {
            element.SetValue(AutoHeightRowCountProperty, value);
        }

        public static void SetAutoWidthColumnCount(UIElement element, int value)
        {
            element.SetValue(AutoWidthColumnCountProperty, value);
        }

        public static BeWoWindow CreateBeWoPopupWindow(double minHeight = 150, double maxWidth = 300, bool withDynamicSize = false)
        {
            var bewoWindow = new BeWoWindow
            {
                MaxWidth = maxWidth,
                MinHeight = minHeight,
                ResizeMode = ResizeMode.NoResize,
                IsMaximizable = false
            };

            if (withDynamicSize)
                bewoWindow.SizeToContent = SizeToContent.WidthAndHeight;

            return bewoWindow;
        }

        public static void SetIsExpanderButtonVisible(UIElement element, Visibility value)
        {
            element.SetValue(IsExpanderButtonVisibleProperty, value);
        }

        public static void SetSelectedItemsList(UIElement element, List<string> value)
        {
            element.SetValue(SelectedItemsListProperty, value);
        }

        internal static ChildItem FindVisualChild<ChildItem>(DependencyObject obj) where ChildItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is ChildItem)
                    return (ChildItem)child;

                var childOfChild = FindVisualChild<ChildItem>(child);

                if (childOfChild != null)
                    return childOfChild;
            }

            return null;
        }

        internal static decimal? GetDecimalValue(decimal? decValue, int decimalPlaces)
        {
            if (decValue != null)
            {
                return Math.Round(decValue.Value, decimalPlaces, MidpointRounding.AwayFromZero);
            }

            return decValue;
        }

        internal static decimal? GetDecimalValueWithMaxDecimal(decimal? decValue, int maxDecimal)
        {
            if (decValue != null)
            {
                string decValueStr = decValue.ToString();
                decValueStr = decValueStr.Replace(".", ",");

                while (decValueStr.Length > 0 && decValueStr.IndexOf(",") > 0 && (decValueStr.EndsWith("0") || decValueStr.EndsWith(",")))
                {
                    decValueStr = decValueStr.Substring(0, decValueStr.Length - 1);
                }

                int decCount = 0;
                if (decValueStr.IndexOf(",") >= 0)
                {
                    decCount = decValueStr.Length - decValueStr.IndexOf(",") - 1;
                }

                if (maxDecimal >= 0 && maxDecimal < decCount)
                {
                    decCount = maxDecimal;
                }

                return GetDecimalValue(decValue, decCount);
            }

            return decValue;
        }

        private static void c_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var c = sender as ListBox;
            var l = new List<string>();

            foreach (var i in c.SelectedItems)
            {
                l.Add(i.ToString());
            }

            SetSelectedItemsList(c, l);
        }

        public static T FindParent<T>(DependencyObject child) where T : DependencyObject
        {
            var parentObject = VisualTreeHelper.GetParent(child);

            if (parentObject == null)
            {
                return null;
            }

            var parent = parentObject as T;

            return parent ?? FindParent<T>(parentObject);
        }
    }
}