Imports BDtelefonos
Imports System.ComponentModel
Imports Microsoft.Win32
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging

Class PagMostrar
  Private odp As ObjectDataProvider = Nothing

  Private Sub Page_Loaded(sender As Object, e As RoutedEventArgs)
    odp = DirectCast(Me.FindResource("pdTelefonos"), ObjectDataProvider)
    Me.DataContext = odp

    ' Manejar el evento CurrentChanged de la vista
    Dim vista As ICollectionView = ObtenerVista()
    AddHandler vista.CurrentChanged, AddressOf vista_CurrentChanged
    ActualizarPosicionReg(TryCast(vista, CollectionView))
  End Sub

  Private Function ObtenerVista() As ICollectionView
    Return CollectionViewSource.GetDefaultView(odp.Data)
  End Function

  Private Sub vista_CurrentChanged(sender As Object, e As EventArgs)
    ActualizarPosicionReg(TryCast(sender, CollectionView))
  End Sub

  Private Sub ActualizarPosicionReg(vista As CollectionView)
    If vista.CurrentItem Is Nothing Then Return
    Dim posicionActual As String = Convert.ToString(vista.CurrentPosition + 1)
    Me.btxPosicionReg.Text = posicionActual
    Me.btxTotalReg.Text = vista.Count.ToString()
    ' Poner una foto ficticia si este campo es Nothing
    If TryCast(vista.CurrentItem, telefono).foto IsNot Nothing Then
      Return
    End If
    Dim fotoFicticia As Bitmap = My.Resources.Resources.unafoto
    Dim ms As New MemoryStream()
    fotoFicticia.Save(ms, ImageFormat.Jpeg)
    TryCast(vista.CurrentItem, telefono).foto = ms.ToArray()
  End Sub

  Private Sub btPrimero_Click(sender As Object, e As RoutedEventArgs)
    Dim vista As ICollectionView = ObtenerVista()
    vista.MoveCurrentToFirst()
  End Sub

  Private Sub btAnterior_Click(sender As Object, e As RoutedEventArgs)
    Dim vista As ICollectionView = ObtenerVista()
    vista.MoveCurrentToPrevious()
    If vista.IsCurrentBeforeFirst Then vista.MoveCurrentToFirst()
  End Sub

  Private Sub btSiguiente_Click(sender As Object, e As RoutedEventArgs)
    Dim vista As ICollectionView = ObtenerVista()
    vista.MoveCurrentToNext()
    If vista.IsCurrentAfterLast Then vista.MoveCurrentToLast()
  End Sub

  Private Sub btUltimo_Click(sender As Object, e As RoutedEventArgs)
    Dim vista As ICollectionView = ObtenerVista()
    vista.MoveCurrentToLast()
  End Sub

  Private Sub ucFiltrar_TextChanged(sender As Object, e As TextChangedEventArgs)
    Dim ct As TextBox = TryCast(e.OriginalSource, TextBox)
    If ct Is Nothing Then Return
    Dim vista As ICollectionView = ObtenerVista()
    If vista.CanFilter Then
      vista.Filter = Function(elemento As Object) _
        DirectCast(elemento, telefono).telefono1.Contains(ct.Text)
    End If
  End Sub

  Private Sub imFoto_MouseDown(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 (*.*)|*.*"
    dlg.ShowDialog()

    If dlg.FileName IsNot Nothing AndAlso dlg.FileName.Length > 0 Then
      Dim bytes As Byte() = File.ReadAllBytes(dlg.FileName)
      Dim vista As ICollectionView = ObtenerVista()
      Dim regActual As telefono = DirectCast(vista.CurrentItem, telefono)
      If regActual IsNot Nothing Then regActual.foto = bytes
    End If
  End Sub

  Private Sub btGuardar_Click(sender As Object, e As RoutedEventArgs)
    guardarCambios("modificar", Nothing)
  End Sub

  Private Sub guardarCambios(op As String, objTfno As telefono)
    ' Obtener el contexto de objetos
    Dim co As bd_telefonos2Entities = TryCast( _
      odp.ObjectInstance, CProveedorDatosTelefono).ContextoDeObjs
    ' Operación: "modificar", "añadir" o "borrar"
    Select Case op
      Case "añadir"
        co.AddTotelefonos(objTfno)
        Exit Select
      Case "borrar"
        co.DeleteObject(objTfno)
        Exit Select
    End Select
    ' Enviar los cambios a la base de datos
    Try
      co.SaveChanges()
      System.Diagnostics.Debug.WriteLine("Cambios realizados")
    Catch ex As Exception
      System.Diagnostics.Debug.WriteLine(ex.InnerException.Message)
    End Try
  End Sub

  Private Sub btAñadir_Click(sender As Object, e As RoutedEventArgs)
    Dim pagFunAgregarTelefono As New PagFunAgregarTelefono()
    AddHandler pagFunAgregarTelefono.Return, AddressOf pagFunAgregarTelefono_Return
    Me.NavigationService.Navigate(pagFunAgregarTelefono)
  End Sub

  Private Sub pagFunAgregarTelefono_Return(sender As Object, e As ReturnEventArgs(Of telefono))
    If e IsNot Nothing Then
      Dim vista As ICollectionView = ObtenerVista()
      ' Añadir el objeto a la colección
      TryCast(vista.SourceCollection, List(Of telefono)).Add(e.Result)
      vista.MoveCurrentToLast()
      ' Añadir el objeto a la base de datos
      guardarCambios("añadir", e.Result)
    End If
  End Sub

  Private Sub btBorrar_Click(sender As Object, e As RoutedEventArgs)
    ' Quitar de la colección el elemento mostrado
    Dim vista As ICollectionView = ObtenerVista()
    If vista.CurrentPosition > -1 Then
      Dim tfno As telefono = DirectCast(vista.CurrentItem, telefono)
      If tfno IsNot Nothing Then
        Dim siguientePosActual As Integer = (vista.CurrentPosition - 1)
        TryCast(vista.SourceCollection, List(Of telefono)).Remove(tfno)
        vista.Refresh()
        If siguientePosActual > -1 Then
          vista.MoveCurrentToPosition(siguientePosActual)
        End If
        ' Borrar el objeto de la base de datos
        guardarCambios("borrar", tfno)
      End If
    End If
  End Sub
End Class
