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 TutorialsSilverlight
{
    using C1.Silverlight.Data.RiaServices;
    using C1.Data;

    public partial class DataSourcesInCode : UserControl
    {
        // This client scope will be used to load the data.
        private RiaClientScope _scope = App.ClientCache.CreateScope();

        public DataSourcesInCode()
        {
            InitializeComponent();

#if LIVEDEMO
            // Hide the Save Changes button in the Live Demo
            // available at http://demo.componentone.com/Silverlight/StudioEntityFramework/
            btnSaveChanges.Visibility = System.Windows.Visibility.Collapsed;
#endif

            // Bind the category combo box to the category view
            // and show the products of the first category in the data grid.

            ClientView<Web.Category> viewCategories = _scope.GetItems<Web.Category>("GetCategories");

            comboBox1.DisplayMemberPath = "CategoryName";
            comboBox1.ItemsSource = viewCategories;
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Rebind the data grid, display the products of the selected category.
            if (comboBox1.SelectedValue != null)
                BindGrid(((Web.Category)comboBox1.SelectedValue).CategoryID);
        }

        private void BindGrid(int categoryID)
        {
            // Filter products by CategoryID on the server
            // and bind them to the data grid.
            dataGrid1.ItemsSource =
                (from p in _scope.GetItems<Web.Product>("GetProducts").AsFiltered(p => p.CategoryID == categoryID)
                 select new
                 {
                     ProductID = p.ProductID,
                     ProductName = p.ProductName,
                     CategoryID = p.CategoryID,
                     CategoryName = p.Category.CategoryName,
                     UnitPrice = p.UnitPrice,
                     QuantityPerUnit = p.QuantityPerUnit,
                     UnitsInStock = p.UnitsInStock,
                     UnitsOnOrder = p.UnitsOnOrder
                 }).AsDynamic(); // AsDynamic() is required for data binding because an anonymous class is used (select new...)
        }

        private void btnSaveChanges_Click(object sender, RoutedEventArgs e)
        {
            App.ClientCache.SaveChanges();
        }
    }
}
