Imports C1.Data
Imports C1.Silverlight.Data.RiaServices
Imports C1.LiveLinq.LiveViews

Partial Public Class MainPage
    Inherits UserControl

    ' A client cache and a client scope that are used to load the data.
    Private _clientCache As RiaClientCache
    Private _scope As RiaClientScope

    Public Sub New()
        InitializeComponent()

        ' Initialize the client cache and the client scope.
        _clientCache = New RiaClientCache(New Web.DomainService1())
        _scope = New RiaClientScope(_clientCache)

        ' Bind a combo box to the list of cities
        ' using a live view of customers grouped by city.
        comboCity.DisplayMemberPath = "City"
        comboCity.ItemsSource =
            (From c In _scope.GetItems(Of Web.Customer)("GetCustomers")
             Group c By Key = c.City Into g = Group
             Order By Key
             Select New With
             {
                 .City = Key,
                 .Customers = g
             }).AsDynamic()
    End Sub

    Private Sub EditOrdersForCustomer()
        If Not (TypeOf listCustomers.SelectedItem Is Web.Customer) Then
            Exit Sub
        End If
        ' Start editing the selected customer.
        Dim customer As Web.Customer = CType(listCustomers.SelectedItem, Web.Customer)

        ' If the customer is already being edited, then select the tab associated with that customer.
        For Each tabItem As TabItem In tabs.Items
            If tabItem.Header = customer.ContactName Then
                tabItem.IsSelected = True
                Exit Sub
            End If
        Next

        ' Create a CustomerControl for the current customer
        ' and display it in the tab control.
        Dim tab As TabItem = New TabItem()
        Dim custControl As CustomerControl = New CustomerControl(Me, tab, customer, _clientCache)
        tab.Header = customer.ContactName
        tab.Content = custControl
        tabs.Items.Add(tab)
        tab.IsSelected = True
    End Sub

    Public Sub CloseRequested(tab As TabItem)
        ' Remove the tab when its Close button is pressed.
        tabs.Items.Remove(tab)
    End Sub

    Private Sub button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        ' Start editing the selected customer.
        EditOrdersForCustomer()
    End Sub
End Class