using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace OData
{
    using OData.ServiceReference1;
    using System.Data.Services.Client;

    public partial class MainPage : UserControl
    {
        static Uri _svcRoot = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
        NorthwindEntities _context = new NorthwindEntities(_svcRoot);

        public MainPage()
        {
            InitializeComponent();

            // bind top grid to categories
            var categories = new DataServiceCollection<Category>();
            _flexCategories.ItemsSource = categories;

            // when the user selects a category, load corresponding products
            _flexCategories.SelectionChanged += _flexCategories_SelectionChanged;

            // load categories
            categories.LoadCompleted += (s, ee) =>
                {
                    if (categories.Continuation != null)
                    {
                        categories.LoadNextPartialSetAsync();
                    }
                    else
                    {
                        _lblCategories.Text = "Categories (Ready)";
                    }
                };
            categories.LoadAsync(_context.Categories);
        }

        void _flexCategories_SelectionChanged(object sender, C1.Silverlight.FlexGrid.CellRangeEventArgs e)
        {
            // get selected category
            var category = _flexCategories.SelectedItem as Category;
            if (category != null)
            {
                // build query to select products in the selected category
                var query = from p in _context.Products
                        where p.CategoryID == category.CategoryID
                        orderby p.ProductName
                        select p;

                // assign new products collection to grid
                var products = new DataServiceCollection<Product>();
                _flexProducts.ItemsSource = products;

                // load products in the selected category
                products.LoadAsync(query);
                products.LoadCompleted += (s, ee) =>
                    {
                        if (products.Continuation != null)
                        {
                            products.LoadNextPartialSetAsync();
                        }
                    };
            }
        }
    }
}
