Imports System.Windows.Navigation

Partial Public Class MainPage
  Inherits UserControl

  Private formLogin As New Login()
  Private svc As RefServicioLogin.LoginClient = Nothing

  Public Sub New()
    InitializeComponent()
    AddHandler formLogin.Closed, AddressOf formLogin_Closed

    Dim uri As New Uri(Application.Current.Host.Source, "../Login.svc")
    svc = New RefServicioLogin.LoginClient("CustomBinding_Login", uri.AbsoluteUri)
    AddHandler svc.AuthenticateCompleted, AddressOf svc_AuthenticateCompleted
    AddHandler svc.SignOutCompleted, AddressOf svc_SignOutCompleted
  End Sub

  Private Sub ContentFrame_Navigated(ByVal sender As Object, ByVal e As NavigationEventArgs) Handles ContentFrame.Navigated
    For Each child As UIElement In LinksStackPanel.Children
      Dim hb As HyperlinkButton = TryCast(child, HyperlinkButton)
      If hb IsNot Nothing AndAlso hb.NavigateUri IsNot Nothing Then
        If hb.NavigateUri = e.Uri Then
          VisualStateManager.GoToState(hb, "ActiveLink", True)
        Else
          VisualStateManager.GoToState(hb, "InactiveLink", True)
        End If
      End If
    Next
  End Sub

  Private Sub ContentFrame_NavigationFailed(ByVal sender As Object, ByVal e As NavigationFailedEventArgs) Handles ContentFrame.NavigationFailed
    e.Handled = True
    Dim errorWindow As ChildWindow = New ErrorWindow(e.Uri)
    errorWindow.Show()
  End Sub

  Private Sub hlInicioSesion_Click(sender As Object, e As RoutedEventArgs)
    If hlInicioSesion.Content.ToString() = "Iniciar sesión" Then
      formLogin.Show()
    Else
      tbBienvenido.Text = ""
      tbSeparador.Visibility = Visibility.Collapsed
      hlInicioSesion.Content = "Iniciar sesión"
      svc.SignOutAsync()
    End If
  End Sub

  Private Sub formLogin_Closed(sender As Object, e As EventArgs)
    If formLogin.DialogResult = True Then
      ' Aquí verificaríamos si las credenciales son válidas 
      svc.AuthenticateAsync(formLogin.txtUsuario.Text,
                            formLogin.txtContraseña.Password)
    End If
  End Sub

  Private Sub svc_AuthenticateCompleted(sender As Object, e As RefServicioLogin.AuthenticateCompletedEventArgs)
    If e.Result Then
      tbSeparador.Visibility = Visibility.Visible


      tbBienvenido.Text = "Bienvenido, " & formLogin.txtUsuario.Text
      hlInicioSesion.Content = "Cerrar sesión"
    Else
      Dim errorWin As ChildWindow = New ErrorWindow("Error:",
                                                    "Las credenciales no son correctas")
      errorWin.Show()
    End If
  End Sub

  Private Sub svc_SignOutCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
    If e.Error IsNot Nothing Then
      Dim s As String = e.Error.Message
      Dim errorWin As ChildWindow = New ErrorWindow("Error:", s)
      errorWin.Show()
    End If
  End Sub
End Class
