Imports ApSilverlightTfnos.ServiceReference1
Imports System.Windows.Data
Imports System.ComponentModel
Imports System.Windows.Media.Imaging

Partial Public Class MainPage
  Inherits UserControl
  Private cliente As Service1Client = Nothing
  Private vistaListaDetalles As PagedCollectionView = Nothing
  Private objTelefonoSeleccionado As telefono = Nothing

  Public Sub New()
    InitializeComponent()
    cliente = New Service1Client()
    AddHandler cliente.ObtenerTfnoCompleted,
      AddressOf cliente_ObtenerTfnoCompleted
    AddHandler cliente.ObtenerTfnosCompleted,
      AddressOf cliente_ObtenerTfnosCompleted
    AddHandler cliente.ActualizarTfnoCompleted,
      AddressOf cliente_ActualizarTfnoCompleted
    AddHandler cliente.AgregarTfnoCompleted,
      AddressOf cliente_AgregarTfnoCompleted
    AddHandler cliente.BorrarTfnoCompleted,
      AddressOf cliente_BorrarTfnoCompleted
  End Sub

  Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
    cliente.ObtenerTfnosAsync()
  End Sub

  Private Sub cliente_ObtenerTfnosCompleted(sender As Object, e As ObtenerTfnosCompletedEventArgs)
    If e.Error IsNot Nothing Then
      tbkInfo.Text = "Error: " & e.Error.Message.ToString()
      popInfo.IsOpen = True
    Else
      vistaListaDetalles = New PagedCollectionView(e.Result)
      vistaListaDetalles.SortDescriptions.Add(
        New SortDescription("apellido1", ListSortDirection.Ascending))
      vistaListaDetalles.MoveCurrentToFirst()
      lstPersonas.ItemsSource = vistaListaDetalles
    End If
  End Sub

  Private Sub lstPersonas_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
    Dim lista As ComboBox = TryCast(sender, ComboBox)
    If lista.SelectedIndex < 0 Then Return

    Dim elementoSeleccionado As Detalles = TryCast(lista.SelectedItem, Detalles)
    ' coincide con vistaListaDetalles.CurrentItem
    If elementoSeleccionado.telefono IsNot Nothing Then
      cliente.ObtenerTfnoAsync(elementoSeleccionado.telefono)
    End If
  End Sub

  Private Sub cliente_ObtenerTfnoCompleted(sender As Object, e As ObtenerTfnoCompletedEventArgs)
    If e.Error IsNot Nothing Then
      tbkInfo.Text = "Error: el teléfono no existe"
      popInfo.IsOpen = True
    Else
      objTelefonoSeleccionado = e.Result
      ' Establecer el contexto de datos del Grid
      LayoutRoot.DataContext = objTelefonoSeleccionado
      ' Poner una foto ficticia si este campo es Nothing
      If objTelefonoSeleccionado.foto IsNot Nothing Then Return
      Dim wbm As WriteableBitmap =
        New WriteableBitmap(0, 0).FromResource("Recursos/foto.jpg")
      imFoto.Source = wbm
    End If
  End Sub

  Private Sub btActualizar_Click(sender As Object, e As RoutedEventArgs)
    cliente.ActualizarTfnoAsync(objTelefonoSeleccionado)
  End Sub

  Private Sub cliente_ActualizarTfnoCompleted(sender As Object, e As AsyncCompletedEventArgs)
    If e.Error IsNot Nothing Then
      tbkInfo.Text = "Error: " & e.Error.Message.ToString()
      popInfo.IsOpen = True
    Else
      ' Actualizar los datos del ComboBox
      Dim objDetallesSeleccionado As Detalles =
        TryCast(lstPersonas.SelectedItem, Detalles)
      objDetallesSeleccionado.apellido1 = objTelefonoSeleccionado.apellido1
      objDetallesSeleccionado.telefono = objTelefonoSeleccionado.telefono1
      tbkInfo.Text = "Actualizado"
      popInfo.IsOpen = True
    End If
  End Sub

  Private Sub imFoto_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
    Dim dlg As New OpenFileDialog()
    dlg.Filter = "ficheros jpg (*.jpg)|*.jpg|" &
                 "ficheros jpeg (*.jpeg)|*.jpeg|" &
                 "ficheros png (*.png)|*.png|" &
                 "Todos (*.*)|*.*"

    If dlg.ShowDialog() = True Then
      If dlg.File.Name Is Nothing OrElse dlg.File.Name.Length = 0 Then
        Return
      End If
      Dim imagen As New WriteableBitmap(0, 0)
      imagen.SetSource(dlg.File.OpenRead())
      imFoto.Source = imagen
    End If
  End Sub

  Private Sub btAgregar_Click(sender As Object, e As RoutedEventArgs)
    cliente.AgregarTfnoAsync(objTelefonoSeleccionado)
  End Sub

  Private Sub cliente_AgregarTfnoCompleted(sender As Object, e As AsyncCompletedEventArgs)
    If e.Error IsNot Nothing Then
      tbkInfo.Text = "Error: ¿existe el teléfono?"
      popInfo.IsOpen = True
    Else
      ' Añadir un nuevo elemento a la vista
      vistaListaDetalles.AddNew()
      Dim objDetallesAgregado As Detalles =
        TryCast(vistaListaDetalles.CurrentAddItem, Detalles)
      objDetallesAgregado.apellido1 = objTelefonoSeleccionado.apellido1
      objDetallesAgregado.telefono = objTelefonoSeleccionado.telefono1
      vistaListaDetalles.CommitNew()
      tbkInfo.Text = "Añadido"
      popInfo.IsOpen = True
    End If
  End Sub

  Private Sub btBorrar_Click(sender As Object, e As RoutedEventArgs)
    cliente.BorrarTfnoAsync(objTelefonoSeleccionado)
  End Sub

  Private Sub cliente_BorrarTfnoCompleted(sender As Object, e As AsyncCompletedEventArgs)
    If e.Error IsNot Nothing Then
      tbkInfo.Text = "Error: ¿existe el teléfono?"
      popInfo.IsOpen = True
    Else
      ' Actualizar los datos del ComboBox
      vistaListaDetalles.Remove(vistaListaDetalles.CurrentItem)
      vistaListaDetalles.MoveCurrentToFirst()
      tbkInfo.Text = "Borrado"
      popInfo.IsOpen = True
    End If
  End Sub

  Private Sub popInfo_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
    popInfo.IsOpen = False
  End Sub
End Class
