Imports System.Windows.Navigation
Imports ApNavSilverlightSvcAps.RefAuthenticationSvc
Imports System.ComponentModel
Imports ApNavSilverlightSvcAps.RefRoleSvc

Partial Public Class MainPage
  Inherits UserControl

  Private formLogin As New Login()
  Private svcAuthentication As AuthenticationServiceClient = Nothing
  Private svcRole As RoleServiceClient = Nothing

  Private usuarioAutenticado As Boolean = False
  Private rolesUsuario As List(Of String) = Nothing

  Public Sub New()
    InitializeComponent()
    AddHandler formLogin.Closed, AddressOf formLogin_Closed
    ' Autenticación
    Dim uri As New Uri(Application.Current.Host.Source,
                       "../AuthenticationService.svc")
    svcAuthentication = New AuthenticationServiceClient(
      "BasicHttpBinding_AuthenticationService", uri.AbsoluteUri)

    AddHandler svcAuthentication.LoginCompleted,
      AddressOf svcAuthentication_LoginCompleted
    AddHandler svcAuthentication.LogoutCompleted,
      AddressOf svcAuthentication_LogoutCompleted
    AddHandler svcAuthentication.IsLoggedInCompleted,
      AddressOf svcAuthentication_IsLoggedInCompleted
    ' Roles
    Dim uriSvcRol As New Uri(Application.Current.Host.Source,
                             "../RoleService.svc")
    svcRole = New RoleServiceClient("BasicHttpBinding_RoleService",
                                     uriSvcRol.AbsoluteUri)
    AddHandler svcRole.GetRolesForCurrentUserCompleted,
      AddressOf svcRole_GetRolesForCurrentUserCompleted

  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 System.Object, e As System.Windows.RoutedEventArgs)
    If hlInicioSesion.Content.ToString() = "Iniciar sesión" Then
      formLogin.Show()
    Else
      tbBienvenido.Text = ""
      tbSeparador.Visibility = Visibility.Collapsed
      hlInicioSesion.Content = "Iniciar sesión"
      svcAuthentication.LogoutAsync()
    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 
      svcAuthentication.LoginAsync(formLogin.txtUsuario.Text,
        formLogin.txtContraseña.Password, String.Empty, False)
    End If
  End Sub

  Private Sub svcAuthentication_LoginCompleted(sender As Object, e As LoginCompletedEventArgs)
    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
    svcAuthentication.IsLoggedInAsync()
  End Sub

  Private Sub svcAuthentication_LogoutCompleted(sender As Object, e As 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
    svcAuthentication.IsLoggedInAsync()
  End Sub

  Private Sub svcAuthentication_IsLoggedInCompleted(sender As Object, e As IsLoggedInCompletedEventArgs)
    usuarioAutenticado = e.Result
    If usuarioAutenticado Then
      svcRole.GetRolesForCurrentUserAsync()
    End If
  End Sub

  Private Sub svcRole_GetRolesForCurrentUserCompleted(sender As Object, e As GetRolesForCurrentUserCompletedEventArgs)
    rolesUsuario = e.Result.ToList()
  End Sub

  Private Sub ContentFrame_Navigating(sender As Object, e As NavigatingCancelEventArgs)
    ' Páginas Home y About
    If e.Uri.OriginalString = "/Home" OrElse
       e.Uri.OriginalString = "/About" Then
      Return
    End If ' continuar
    ' Resto de páginas: Mostrar, Agregar y Borrar
    If Not usuarioAutenticado Then
      AccesoDenegado(e)
      ' Si está autenticado tiene acceso a Mostrar. Ahora:
    ElseIf e.Uri.OriginalString <> "/Mostrar" AndAlso
           rolesUsuario.Count = 0 Then
      AccesoDenegado(e)
    Else
      ' "miembros" o "administradores"
      For Each role As String In rolesUsuario
        ' Ambos pueden Agregar, pero Borrar sólo los administradores
        If e.Uri.OriginalString = "/Borrar" AndAlso
           role <> "administradores" Then
          AccesoDenegado(e)
        End If
      Next
    End If
  End Sub

  Private Sub AccesoDenegado(e As NavigatingCancelEventArgs)
    Dim window As New ErrorWindow("Acceso denegado",
      "No está autorizado para acceder a esta página")
    window.Show()
    e.Cancel = True
  End Sub
End Class
