using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using C1.Silverlight.DataGrid;

namespace C1DataGrid_Ria
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			InitializeComponent();
		}

		private void _submitButton_Click(object sender, RoutedEventArgs e)
		{
			// Submit changes to the server
			_dataGrid.IsLoading = true;
			_myDataSource.SubmitChanges();
		}

		private void _rejectButton_Click(object sender, RoutedEventArgs e)
		{
			// Reject changes
			_myDataSource.DomainContext.RejectChanges();
			CheckChanges();
		}

		// Disable submit/reject buttons when there are pending changes in the row
		private void _dataGrid_BeginningRowEdit(object sender, DataGridEditingRowEventArgs e)
		{
			_submitButton.IsEnabled = false;
			_rejectButton.IsEnabled = false;
		}

		// Enable/disable submit/reject buttons after pending changes are committed
		private void _dataGrid_CommittingRowEdit(object sender, DataGridEditingRowEventArgs e)
		{
			CheckChanges();
		}

		// Enable/disable submit/reject buttons after pending changes are canceled
		private void _dataGrid_CancelingRowEdit(object sender, DataGridEditingRowEventArgs e)
		{
			CheckChanges();
		}

		// Enable/disable submit/reject buttons after rows deleted
		private void _dataGrid_RowsDeleted(object sender, DataGridRowsDeletedEventArgs e)
		{
			CheckChanges();
		}

		// Check the pending changes to submit/reject and enable/disable buttons according
		// to this.
		private void CheckChanges()
		{
			EntityChangeSet changeSet = _myDataSource.DomainContext.EntityContainer.GetChanges();
			_changeText.Text = changeSet.ToString();

			bool hasChanges = _myDataSource.HasChanges;
			_submitButton.IsEnabled = hasChanges;
			_rejectButton.IsEnabled = hasChanges;
		}

		// Check for errors when submitting changes to the server
        private void SubmitCompleted(object sender, SubmittedChangesEventArgs e)
		{
			_dataGrid.IsLoading = false;
			if (e.HasError)
			{
				MessageBox.Show(string.Format("Submit Failed: {0}", e.Error.Message));
				e.MarkErrorAsHandled();
			}
			CheckChanges();
		}
	}
}
