using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace OrderEntrySystem
{
    /// <summary>
    /// Interaction logic for MultiEntityView.xaml
    /// </summary>
    public partial class MultiEntityView : UserControl
    {
        private ColumnUtility columnUtility;

        public MultiEntityView(IMultiEntityViewModel viewModel)
        {
            this.columnUtility = new ColumnUtility();
            this.DataContext = viewModel;
            InitializeComponent();
            this.LayoutUpdated += this.OnLayoutUpdated;
        }

        private void OnLayoutUpdated(object sender, EventArgs e)
        {
            if (this.entityListView.View != null)
            {
                this.columnUtility.ResizeColumns((this.entityListView.View as GridView).Columns, this.entityListView.ActualWidth);
                this.LayoutUpdated -= this.OnLayoutUpdated;
            }
        }

        private void BuildGrid()
        {
            Type viewModeltype = (this.DataContext as IMultiEntityViewModel).Type;
            var props = from p in viewModeltype.GetProperties()
                        where DisplayUtil.HasColumn(p)
                        orderby DisplayUtil.GetColumnSequence(p)
                        select p;

            GridView gridView = new GridView();

            foreach (PropertyInfo p in props)
            {
                gridView.Columns.Add(this.columnUtility.BuildColumn(p));
            }

            this.entityListView.View = gridView;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.BuildGrid();

        }

        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.entityListView.View != null)
            {
                this.columnUtility.ResizeColumns((this.entityListView.View as GridView).Columns, this.entityListView.ActualWidth);
            }
        }
    }
}
