Imports System.Web
Imports System.Threading.Tasks

Public Class LoginCertCallback
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        RegisterAsyncTask(New PageAsyncTask(AddressOf Procesar))
    End Sub

    Private Async Function Procesar() As Task
        Dim state = Convert.ToString(Request.QueryString("state"))
        If String.IsNullOrWhiteSpace(state) Then
            RedirigirConError("No se recibió el estado del acceso con certificado.")
            Return
        End If

        Dim cacheKey = GetCacheKey(state)
        Dim dni = TryCast(HttpRuntime.Cache(cacheKey), String)
        If Not String.IsNullOrWhiteSpace(dni) Then
            HttpRuntime.Cache.Remove(cacheKey)
        End If

        If String.IsNullOrWhiteSpace(dni) Then
            RedirigirConError("No se pudo recuperar el DNI del acceso con certificado.")
            Return
        End If

        Dim result = Await _Default.cargarListadoCertificado(dni)
        If String.Equals(result, "home.aspx", StringComparison.OrdinalIgnoreCase) OrElse
            String.Equals(result, "selModo.aspx", StringComparison.OrdinalIgnoreCase) Then

            Response.Redirect(result, False)
            Context.ApplicationInstance.CompleteRequest()
            Return
        End If

        RedirigirConError(result)
    End Function

    Private Sub RedirigirConError(message As String)
        Dim safeMessage = If(String.IsNullOrWhiteSpace(message), "No se pudo completar el acceso con certificado.", message)
        Response.Redirect("Default.aspx?certError=" & HttpUtility.UrlEncode(safeMessage), False)
        Context.ApplicationInstance.CompleteRequest()
    End Sub

    Private Shared Function GetCacheKey(state As String) As String
        Return "CertLoginState:" & state.Trim()
    End Function
End Class
