using System;
using System.Linq;
using System.Windows.Controls;
using Telerik.Windows.Controls.DomainServices;

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

			this.customersDataSource.QueryName = "GetCustomers";
			this.customersDataSource.PageSize = 20;
			this.customersDataSource.AutoLoad = true;
		}
		
		DateTime startTime;
		private void OnCustomersDataSourceLoadingData(object sender, LoadingDataEventArgs e)
		{
			startTime = DateTime.Now;
			var query = e.Query.Query.ToString().Replace("SilverlightApplication1.Web.Models.Customer[]", "Customers");
			this.debugTextBox.Text += string.Format("{0}: Sending query to server: {1}\r\n"
				, this.startTime.ToString("hh:mm:ss.fff")
				, query);
		}

		private void OnCustomersDataSourceLoadedData(object sender, LoadedDataEventArgs e)
		{
			if (e.HasError)
			{
				e.MarkErrorAsHandled();
				this.debugTextBox.Text += string.Format("{0}: Server returned the following error: {1}\r\n"
					, DateTime.Now.ToString("hh:mm:ss.fff")
					, e.Error);
			}
			else
			{
				var elapsedTime = DateTime.Now - this.startTime;
				this.debugTextBox.Text += string.Format("{0}: Server returned {1} entities {2} ms\r\n"
					, DateTime.Now.ToString("hh:mm:ss.fff")
					, e.Entities.Count()
					, elapsedTime.Milliseconds);
			}
		}

		private void OnDebugTextBoxTextChanged(object sender, TextChangedEventArgs e)
		{
			this.debugScrollViewer.ScrollToVerticalOffset(this.debugScrollViewer.ExtentHeight);
		}

		private void OnRadGridViewAutoGeneratingColumn(object sender, Telerik.Windows.Controls.GridViewAutoGeneratingColumnEventArgs e)
		{
			e.Column.ShowDistinctFilters = false;
		}
	}
}
