using System;
using System.Windows.Controls;
using System.Windows.Data;
using C1.Silverlight.Data;
using C1.Silverlight.Extended;
using C1.Silverlight.Extended.PropertyGrid;
using C1.Silverlight;

namespace C1Data_Demo
{
	public partial class DemoData : UserControl
	{
		private DataTable dt;

		public DemoData()
		{
			InitializeComponent();

			// Create data table
			DataTable initialDataTable = CreateDataTable();

			// Configure PropertyGrid
			TypeEditor typeEditor = new TypeEditor();
			_propertyGrid.AvailableEditors.Add(typeEditor);
			_propertyGrid.SelectedObject = initialDataTable;

			CollectionEditor rowsEditor = new CollectionEditor(_propertyGrid) { CanUserAddItems = false, CanUserRemoveItems = false, CanUserSortItems = false };
			CollectionEditor defaultViewEditor = new CollectionEditor(_propertyGrid) { CanUserAddItems = false, CanUserRemoveItems = false, CanUserSortItems = false };
			_propertyGrid.PropertyAttributes.Add(new PropertyAttribute() { MemberName = "ChildRelations", ReadOnly = true });
			_propertyGrid.PropertyAttributes.Add(new PropertyAttribute() { MemberName = "ParentRelations", ReadOnly = true });
			_propertyGrid.PropertyAttributes.Add(new PropertyAttribute() { MemberName = "Rows", Editor = rowsEditor });
			_propertyGrid.PropertyAttributes.Add(new PropertyAttribute() { MemberName = "DefaultView", Editor = defaultViewEditor });
			_propertyGrid.PropertyAttributes.Add(new PropertyAttribute() { MemberName = "DefaultValue", PropertyBinding = new Binding("DefaultValue") { Converter = typeEditor.GetConverter(), Mode = BindingMode.TwoWay } });
			_propertyGrid.PropertyBoxesLoaded += new EventHandler(_propertyGrid_PropertyBoxesLoaded);

			// Set DataGrid source
			_dataGrid.ItemsSource = initialDataTable.DefaultView;
		}

		void _propertyGrid_PropertyBoxesLoaded(object sender, EventArgs e)
		{
			CollectionEditor colEditor = _propertyGrid.GetEditorControl("Columns") as CollectionEditor;
			if (colEditor != null)
			{
				colEditor.ValueChanging -= new EventHandler<PropertyCommitChangesEventsArgs>(colEditor_ValueChanging);
				colEditor.ValueChanging += new EventHandler<PropertyCommitChangesEventsArgs>(colEditor_ValueChanging);
                colEditor.ValueChanged -= new System.ComponentModel.PropertyChangedEventHandler(colEditor_ValueChanged);
                colEditor.ValueChanged += new System.ComponentModel.PropertyChangedEventHandler(colEditor_ValueChanged);
			}
		}

        void colEditor_ValueChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // refresh DataTable after columns collection has been changed
            RefreshData();
            _dataGrid.Reload(true);
        }

		void colEditor_ValueChanging(object sender, PropertyCommitChangesEventsArgs e)
		{
            System.Collections.Generic.List<string> columnNames = new System.Collections.Generic.List<string>(); // store column names to check for ambiguous names
			foreach (DataColumn col in e.NewList)
			{
				if (string.IsNullOrEmpty(col.Name)) 
				{
					e.Cancel = true;
					C1MessageBox.Show("All column should have a name", "Error", C1MessageBoxIcon.Error);
					break;
				}
                if (columnNames.Contains(col.Name))
                {
                    e.Cancel = true;
                    C1MessageBox.Show("Ambiguous column name. Columns should have unique names", "Error", C1MessageBoxIcon.Error);
                    break;
                }
                columnNames.Add(col.Name);
			}
        }


		public DataTable CreateDataTable()
		{
			// Create DataSet
			DataSet ds = new DataSet();

			// Create DataTable
			dt = new DataTable("DynamicTable");
			ds.Tables.Add(dt);

			// Create initial columns
			dt.Columns.Add(new DataColumn() { Name = "AutoIncrement", DataType = typeof(int), AutoIncrement = true, ReadOnly = true });
			dt.Columns.Add(new DataColumn() { Name = "String", DataType = typeof(string) });
			dt.Columns.Add(new DataColumn() { Name = "Int32", DataType = typeof(int) });

			// create initial rows
			RefreshData();

            return dt;
		}

		private void RefreshData()
		{
			dt.Rows.Clear();
			for (int i = 0; i < 10; i++)
			{
				DataRow newRow = dt.NewRow();
				for (int j = 0; j < dt.Columns.Count; j++)
				{
					if (string.IsNullOrEmpty(dt.Columns[j].Expression) && 
						(dt.Columns[j].DefaultValue == null) && 
						(dt.Columns[j].AutoIncrement == false))
					{
						newRow[j] = Convert.ChangeType(j, dt.Columns[j].DataType, null);
					}
				}
				dt.Rows.Add(newRow);
			}
		}
	}
}
