Imports System.Net.Mail

Public Class ForgotPassword
    Inherits System.Web.UI.Page

#Region "Event handling"

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Response.Redirect("Login.aspx")
    End Sub

    Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click, btnDefault.Click
        Try

            Dim email = txtEmail.Text
            Dim account = New Logic.DriverAccount(email)

            Dim reset As New Logic.PasswordReset(account)
            reset.Create()
            _SendEmail(account, reset.code)

        Catch ex As ArgumentOutOfRangeException
            ' we pretend this didn't happen, so they don't know if account exists

        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try

        ' success
        Response.Redirect("ForgotPassword_Success.aspx")

    End Sub

#End Region

#Region "Internals"

    Private Sub _SendEmail(account As Logic.DriverAccount, code As String)

        ' variables we'll need
        Dim base = My.Settings.baseUrl & "Driver/ResetPassword.aspx?code="
        Dim safeName = HttpUtility.HtmlEncode(account.nameFull)
        Dim safeCode = HttpUtility.UrlEncode(code)

        ' define the message
        Dim message = "
            Dear %%NAME%%,%%CRLF2%%

            A password reset has been requested for your TCS Online Portal account.%%CRLF2%%

            To change your password, please visit 
            <a href='%%BASE%%%%CODE%%'>%%BASE%%%%CODE%%</a>.%%CRLF2%%

            This code will expire in 24 hours.%%CRLF2%%

            Sincerely,%%CRLF%%
            TCS
            "

        ' Replace vars in message string
        Dim parameters As New Dictionary(Of String, String)
        With parameters
            .Add("CRLF", "<br/>")
            .Add("CRLF2", "<br/><br/>")
            .Add("BASE", base)
            .Add("CODE", safeCode)
            .Add("NAME", safeName)
        End With
        For Each param In parameters
            Dim key = "%%" & param.Key & "%%"
            Dim replacement = param.Value
            message = message.Replace(key, replacement)
        Next

        ' send the email
        Dim email As New MailMessage(My.Settings.emailForgotPassword, account.email)
        With email
            .Subject = "TCS Online Portal Password Reset"
            .Body = message
            .IsBodyHtml = True
        End With

        Dim smtp As New SmtpClient
        smtp.Send(email)

    End Sub

#End Region

End Class