Imports System.Collections.Specialized
Imports System.ComponentModel

Class CTelefonoBLL
  Private bd As New CTelefonoDAL()
  Private tfnoAnterior As String

  Public Function ObtenerFilaTfnos(tfno As String) As CTelefonoBO
    Return bd.ObtenerFilaTfnos(tfno)
  End Function

  Public Function ObtenerFilasTfnos() As ColCTelefonos
    Dim coTfnos As ColCTelefonos = bd.ObtenerFilasTfnos()
    AddHandler coTfnos.CollectionChanged, AddressOf ControladorCollectionChanged
    ' Asignar un controlador para los eventos ItemBeginEdit e 
    ' ItemEndEdit del objeto colección coTfnos
    AddHandler coTfnos.ItemEndEdit, AddressOf ControladorItemEndEdit
    AddHandler coTfnos.ItemBeginEdit, AddressOf ControladorItemBeginEdit
    Return coTfnos
  End Function

  Private Sub ControladorCollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
    If e.Action = NotifyCollectionChangedAction.Remove Then
      For Each item As Object In e.OldItems
        Dim obj As CTelefonoBO = TryCast(item, CTelefonoBO)
        BorrarFilaTfnos(obj.Telefono)
      Next
    ElseIf e.Action = NotifyCollectionChangedAction.Add Then
      For Each item As Object In e.NewItems
        Dim obj As CTelefonoBO = TryCast(item, CTelefonoBO)
        obj.Nombre = "nombre"
        obj.Direccion = "dirección"
        obj.Telefono = "000000000"
        obj.Observaciones = "Ninguna"
      Next
    End If
  End Sub

  Private Sub ControladorItemBeginEdit(sender As IEditableObject)
    tfnoAnterior = TryCast(sender, CTelefonoBO).Telefono
  End Sub

  Private Sub ControladorItemEndEdit(sender As IEditableObject)
    Dim obj As CTelefonoBO = TryCast(sender, CTelefonoBO)
    If obj.Modificado = False Then Return
    If ObtenerFilaTfnos(obj.Telefono) Is Nothing Then
      If ObtenerFilaTfnos(tfnoAnterior) IsNot Nothing Then
        BorrarFilaTfnos(tfnoAnterior)
      End If
      InsertarFilaTfnos(obj)
    Else
      ActualizarNomDirObs(obj)
    End If
  End Sub

  Public Function InsertarFilaTfnos(bo As CTelefonoBO) As String
    Return bd.InsertarFilaTfnos(bo)
  End Function

  Public Sub BorrarFilaTfnos(tfno As String)
    bd.BorrarFilaTfnos(tfno)
  End Sub

  Public Sub ActualizarNomDirTfnObs(bo As CTelefonoBO, tfnoAntiguo As String)
    bd.ActualizarNomDirTfnObs(bo, tfnoAntiguo)
  End Sub

  Public Sub ActualizarNomDirObs(bo As CTelefonoBO)
    bd.ActualizarNomDirObs(bo)
  End Sub
End Class
