Imports System.Data.SqlClient
Imports System.Threading

Public Class EmailAppLink
    Inherits InternalAPIBase

    Protected Sub Page_Load() Handles Me.Load
        Try
            Dim contractId As Integer = Request.Form("contractId")
            Dim driverName As String = Request.Form("driverName")
            Dim driverEmail As String = Request.Form("driverEmail")

            VerifyContractAccess(contractId)

            SendEmail(contractId, driverName, driverEmail)
            RespondSuccess()

        Catch ex As ThreadAbortException
            'nop
        Catch ex As Exception
            RespondError(ex)
        End Try
    End Sub

    Private Sub SendEmail(contractId, driverName, driverEmail)

        Dim senderId As Integer, subject As String, template As String
        Dim customerName As String
        Using connection As New SqlConnection(Logic.Database.ConnectionString) 'My.Settings.connectionString)
            connection.Open()
            Dim cmd As New SqlCommand("", connection)

            ' Get the email template
            cmd.CommandText =
                "SELECT emailDriverAppLinkFromId, emailDriverAppLinkSubject, emailDriverAppLinkBody FROM Company"
            Using dReader = cmd.ExecuteReader()
                dReader.Read()
                senderId = dReader("emailDriverAppLinkFromId")
                subject = dReader("emailDriverAppLinkSubject")
                template = dReader("emailDriverAppLinkBody")
            End Using

            ' Pull in the contract name, which is the only template param we're missing
            cmd.CommandText =
                "SELECT cust.Name 
                FROM ServiceContract sc LEFT JOIN Customer cust on SC.CustomerID=cust.ID 
                WHERE sc.ID=@contractId"
            cmd.Parameters.AddWithValue("contractId", contractId)
            customerName = cmd.ExecuteScalar()
        End Using

        ' Build the template body
        Dim params As New Dictionary(Of String, String) From {
            {"CONTRACTID", contractId},
            {"CUSTOMERNAME", customerName},
            {"DRIVERNAME", driverName},
            {"STARTURL", My.Settings.baseUrl & "Driver/StartApplication.aspx?clientId=" & contractId}}
        For Each param In params
            template = template.Replace("#" & param.Key & "#", param.Value)
        Next
        template = template.Replace("'", "") ' in case other software doesn't sanitize

        ' Send the email
        Call New Logic.AutomationServer_EmailsSent() With {
            .EmailFromId = senderId,
            .EmailTo = driverEmail,
            .EmailSubject = subject,
            .EmailBody = template,
            .KeepSubject = True
        }.Create()

    End Sub

End Class