using System;
using System.Windows;
using System.Windows.Controls;

namespace InABox.DynamicGrid
{
    /// <summary>
    ///     Interaction logic for KanbanGrid.xaml
    /// </summary>
    public partial class DynamicKanbanGrid : UserControl
    {
        private static readonly DependencyPropertyKey ColumnsPropertyKey =
            DependencyProperty.RegisterReadOnly(
                "Columns",
                typeof(FreezableCollection<DynamicKanbanColumn>),
                typeof(DynamicKanbanGrid),
                new FrameworkPropertyMetadata(new FreezableCollection<DynamicKanbanColumn>()
                )
            );

        public static readonly DependencyProperty ColumnsProperty = ColumnsPropertyKey.DependencyProperty;

        private readonly FreezableCollection<DynamicKanbanColumn> columns;

        public DynamicKanbanGrid()
        {
            InitializeComponent();
            columns = new FreezableCollection<DynamicKanbanColumn>();
            columns.Changed += Columns_Changed;
            //columns.CollectionChanged += Columns_CollectionChanged;
            SetValue(ColumnsPropertyKey, columns);
        }

        public FreezableCollection<DynamicKanbanColumn> Columns => (FreezableCollection<DynamicKanbanColumn>)GetValue(ColumnsProperty);

        private void Columns_Changed(object sender, EventArgs e)
        {
            _grid.Children.Clear();
            _grid.ColumnDefinitions.Clear();

            foreach (var column in columns)
            {
                column.OnCollapsed += Column_OnCollapsed;
                _grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                column.SetValue(Grid.ColumnProperty, _grid.ColumnDefinitions.Count - 1);
                _grid.Children.Add(column);
            }
        }

        private void Column_OnCollapsed(object sender, bool collapsed)
        {
            var index = columns.IndexOf((DynamicKanbanColumn)sender);
            _grid.ColumnDefinitions[index].Width = new GridLength(1, collapsed ? GridUnitType.Auto : GridUnitType.Star);
        }
    }
}