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;

using NorthwindClient.NorthwindService;
using System.Data.Services.Client;
using System.IO.IsolatedStorage;

namespace NorthwindClient
{
    public partial class Page : UserControl
    {
        List<Products> lastResult = null;
        public Page()
        {
            InitializeComponent();

            // načtení uložené hodnoty
            if (IsolatedStorageSettings.ApplicationSettings.Contains("search"))
            {
                string s = IsolatedStorageSettings.ApplicationSettings["search"].ToString();
                txtSearch.Text = s;
                Search(s);
            }
        }

        private void cmdSearch_Click(object sender, RoutedEventArgs e)
        {
            string s = txtSearch.Text.Trim();
            Search(s);
            IsolatedStorageSettings.ApplicationSettings["search"] = s;
        }
        
        public void Search(string filter)
        {
            NorthwindEntities ctx = new NorthwindEntities(new Uri("Northwind.svc", UriKind.Relative));

            var query = from p in ctx.Products.Expand("Categories").Expand("Suppliers")
                        orderby p.ProductName
                        select p;

            if (filter.Length > 0)
            {
                query = (IOrderedQueryable<Products>)query.Where(p => p.ProductName.StartsWith(filter));
            }

            DataServiceQuery<Products> queryCall = (DataServiceQuery<Products>)query;
            queryCall.BeginExecute(new AsyncCallback(OnData), queryCall);
        }

        private void OnData(IAsyncResult result)
        {
            DataServiceQuery<Products> queryResult = (DataServiceQuery<Products>)result.AsyncState;

            lastResult = queryResult.EndExecute(result).ToList<Products>();         

            grdMain.SelectedIndex = -1;
            grdMain.ItemsSource = lastResult;
        }

        private void cmdShowSupplier_Click(object sender, RoutedEventArgs e)
        {
            frmSupplierView.DataContext = (Suppliers)((Button)sender).Tag;            
            frmSupplierView.Visibility = Visibility.Visible;
        }
    }
}
