Imports System.Data.SqlClient
Imports System.Net

Public Class AttachmentImage
    Inherits System.Web.UI.Page

    ' On init, make sure we are on HTTPS (if set in config)
    Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        If My.Settings.httpsOnly Then
            _SecurePage()
        End If
    End Sub

    ' On load, process query params to return what we want
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim context = Logic.Conversion.ToString(Request.Params("context"))
        Dim contextId = Logic.Conversion.ToInteger(Request.Params("id"))
        Dim name = Logic.Conversion.ToString(Request.Params("name"))
        If context = "" And contextId = 0 And name = "" Then
            Exit Sub
        End If

        Try
            Dim image = LoadImage(context, contextId, name)
            Dim filename = Regex.Replace(image.Key, "[^\w\.]", "")
            Dim data = image.Value

            With Response
                .Buffer = True
                .Charset = ""
                .Cache.SetCacheability(HttpCacheability.NoCache)
                .ContentType = MimeMapping.GetMimeMapping(filename)
                .AddHeader("content-disposition", "attachment;filename=" & filename)
                .BinaryWrite(image.Value)
                .Flush()
                .End()
            End With

        Catch ex As Threading.ThreadAbortException
        Catch ex As Exception
            ' For almost all errors, we just want 404 so they can't query our db info
            Response.StatusCode = HttpStatusCode.NotFound
            Response.End()
        End Try

    End Sub

#Region "Internals"

    ' Make us use https
    Private Sub _SecurePage()
        Dim ServerName As String = Server.UrlEncode(Request.ServerVariables.Item("SERVER_NAME"))
        Dim FilePath As String = Request.Url.PathAndQuery
        If Not Request.IsSecureConnection Then
            Response.Redirect("https://" & ServerName & FilePath)
        End If
    End Sub

#End Region

#Region "Image Loading"

    ' Call this
    Function LoadImage(context As String, contextId As Integer, name As String) As KeyValuePair(Of String, Byte())
        Select Case context
            Case "DPQ" : Return _LoadDPQImage(contextId, name)
            Case Else : Throw New ArgumentException(context)
        End Select
    End Function

    ' Internal
    Private Function _LoadDPQImage(contextId As Integer, column As String) As KeyValuePair(Of String, Byte())

        ' construct query with a whitelist of column options
        Dim cmdGet = "
            SELECT @column, @columnFilename 
            FROM web_DriverApplication 
            WHERE id=@appId AND driverAccountId=@driverId"
        Select Case column
            Case "CurrentLicenseFront" : cmdGet = cmdGet.Replace("@column", column)
            Case "CurrentLicenseBack" : cmdGet = cmdGet.Replace("@column", column)
            Case "MedicalRegistryCard" : cmdGet = cmdGet.Replace("@column", column)
            Case Else : Throw New ArgumentException(column)
        End Select

        ' connect and get it
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand(cmdGet, connection)
            cmd.Parameters.AddWithValue("appId", contextId)
            cmd.Parameters.AddWithValue("driverId", SessionVars.DriverId(Session))

            Dim dReader = cmd.ExecuteReader()
            If Not dReader.Read() Then
                Throw New Exception("Not found")
            End If

            Dim image = CType(dReader(0), Byte())
            Dim filename = CType(dReader(1), String)
            Return New KeyValuePair(Of String, Byte())(filename, image)

        End Using

    End Function


#End Region

End Class