using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Windows.Data;

namespace BeWo.Converter
{
    public class IListT2DataTableConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is IList && value.GetType().IsGenericType)
            {
                DataTable lResult = new DataTable();

                Type lGenericType = value.GetType().GetGenericArguments()[0];

                lResult.TableName = lGenericType.FullName;
                lResult.Columns.Add("item");

                foreach (var iProp in lGenericType.GetProperties())
                {
                    lResult.Columns.Add(iProp.Name);
                }

                Hashtable lRows2Objects = new Hashtable();

                foreach (var iItem in value as IList)
                {
                    var iRow = lResult.NewRow();
                    iRow["item"] = iItem;

                    lRows2Objects.Add(iRow, iItem);

                    foreach (var iProp in lGenericType.GetProperties())
                    {
                        iRow[iProp.Name] = iProp.GetValue(iItem, null);
                    }

                    lResult.Rows.Add(iRow);
                }

                lResult.RowChanged += (s, e) =>
                    {
                        foreach (var iProp in lGenericType.GetProperties())
                        {
                            iProp.SetValue(lRows2Objects[e.Row], e.Row[iProp.Name], null);
                        }
                    };

                return lResult;
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}