using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using IdeaBlade.Core;
using IdeaBlade.EntityModel;
using Telerik.Windows.Data;
using System.Linq;

namespace DevForceSilverlightApp
{
	public class MainPageViewModel
	{
		private NorthwindIBEntities mgr;

		public MainPageViewModel()
		{
			this.mgr = new NorthwindIBEntities();
			AsyncMainPageViewModel();
		}

		async void AsyncMainPageViewModel()
		{
			this.Employees = new ObservableCollection<Employee>();
			var query = this.mgr.Employees;
			var results = await query.ExecuteAsync();
			results.ForEach(Employees.Add);
		}

		async Task LoadData(int startIndex, int itemCount)
		{
			try
			{
				IEntityQuery<Order> qry = this.mgr.Orders.OrderBy(o => o.OrderID).Skip(startIndex).Take(itemCount);

				var result = await this.mgr.ExecuteQueryAsync<Order>(qry);

				Debug.WriteLine(string.Format("loaded items from {0} to {1}", startIndex, startIndex + itemCount));

				this.Orders.Load(startIndex, result);
			}
			catch (Exception)
			{
				MessageBox.Show("Opa");
			}
		}

		public ObservableCollection<Employee> Employees
		{
			get;
			private set;
		}

		private VirtualQueryableCollectionView<Order> orders;
		public VirtualQueryableCollectionView<Order> Orders
		{
			get
			{
				if (this.orders == null)
				{
					this.orders = new VirtualQueryableCollectionView<Order>() { LoadSize = 20 };
					Deployment.Current.Dispatcher.InvokeAsync(
						async () =>
						{
							int result = await this.mgr.Orders.AsScalarAsync().Count();
							this.orders.VirtualItemCount = result;

							this.orders.ItemsLoading += async (s, e) =>
							{
								await this.LoadData(e.StartIndex, e.ItemCount);
							};
							//this.orders.ItemsLoaded += (s, e) =>
							//	{
							//		Debug.WriteLine(string.Format("loaded items from {0} to {1}", e.StartIndex, e.StartIndex + e.Items.AsQueryable().Count()));
							//	};
							await this.LoadData(0, this.orders.LoadSize);
						});
				}
				return this.orders;
			}
		}
	}
}
