Imports System.Data.SqlClient
Imports System.IO
Imports CrystalDecisions.CrystalReports.Engine
Imports ReportingClass

Public Class CurrentLicense
    Inherits System.Web.UI.Page

    Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try

            ' gotta set these here
            imgBack.Attributes.Add("data-for", uplBack.ClientID)
            imgFront.Attributes.Add("data-for", uplFront.ClientID)

            ' load the page on entry, save on exit
            If Not Page.IsPostBack Then
                _LoadForm()
            Else
                _SaveForm()
                _SaveDocument()
            End If

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

    Private Sub _LoadForm()

        Dim cmdGet = "
            SELECT CurrentLicenseFrontFilename, CurrentLicenseBackFilename
            FROM web_DriverApplication
            WHERE id=@appId"

        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand(cmdGet, connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)

            Dim dReader = cmd.ExecuteReader()
            dReader.Read()
            If TypeOf dReader(0) IsNot DBNull Then
                imgFront.ImageUrl = "/_assets/AttachmentImage.aspx?context=DPQ&name=CurrentLicenseFront&id=" & Master.app.id
            End If
            If TypeOf dReader(1) IsNot DBNull Then
                imgBack.ImageUrl = "/_assets/AttachmentImage.aspx?context=DPQ&name=CurrentLicenseBack&id=" & Master.app.id
            End If

        End Using

    End Sub

    Private Sub _SaveForm()

        Dim cmdSaveFront = "
            UPDATE web_DriverApplication
            SET CurrentLicenseFront=@front, CurrentLicenseFrontFilename=@frontName
            WHERE id=@appId"
        Dim cmdSaveBack = "
            UPDATE web_DriverApplication
            SET CurrentLicenseBack=@back, CurrentLicenseBackFilename=@backName
            WHERE id=@appId"

        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand("", connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)

            If uplFront.HasFile Then
                Dim filename = uplFront.FileName
                If filename.Length > 50 Then
                    filename = filename.Substring(filename.Length - 50)
                End If

                cmd.CommandText = cmdSaveFront
                cmd.Parameters.AddWithValue("front", uplFront.FileBytes)
                cmd.Parameters.AddWithValue("frontName", filename)
                cmd.ExecuteNonQuery()
            End If

            If uplBack.HasFile Then
                Dim filename = uplBack.FileName
                If filename.Length > 50 Then
                    filename = filename.Substring(filename.Length - 50)
                End If

                cmd.CommandText = cmdSaveBack
                cmd.Parameters.AddWithValue("back", uplBack.FileBytes)
                cmd.Parameters.AddWithValue("backName", filename)
                cmd.ExecuteNonQuery()
            End If

        End Using

        Page.Validate()
        If Page.IsValid Then
            Master.EnableNextPage()
        End If

    End Sub

    Private Sub _SaveDocument()
        
        Dim PictureFront As Byte() = Nothing
        Dim PictureBack As Byte() = Nothing
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()
            Dim cmdGet = "SELECT CurrentLicenseFront, CurrentLicenseBack FROM web_DriverApplication WHERE Id=@appId"
            Dim cmd As New SqlCommand(cmdGet, connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)
            Dim dReader = cmd.ExecuteReader()
            If dReader.Read() Then
                If TypeOf dReader(0) IsNot DBNull Then PictureFront = dReader(0)
                If TypeOf dReader(1) IsNot DBNull Then PictureBack = dReader(1)
            End If
        End Using

        Dim ReportDataSet As New dsAppGeneric
        Dim ReportTableAdapter As New dsAppGenericTableAdapters.AppGenericTableAdapter

        Using Report As New crptAppCurrentLicense
            ReportTableAdapter.Fill(ReportDataSet.AppGenericDataTable, Master.app.id)
            Report.SetDataSource(ReportDataSet)

            Dim PictureBox As PictureObject = Report.ReportDefinition.ReportObjects("picFront")
            Dim LinkedFormula As FormulaFieldDefinition = Report.DataDefinition.FormulaFields("pathFront")
            Dim PathFront = Reporting.SetPictureFromData(PictureBox, LinkedFormula, PictureFront, New Drawing.Size(11224, 4800))

            PictureBox = Report.ReportDefinition.ReportObjects("picBack")
            LinkedFormula = Report.DataDefinition.FormulaFields("pathBack")
            Dim PathBack = Reporting.SetPictureFromData(PictureBox, LinkedFormula, PictureBack, New Drawing.Size(11224, 4800))

            Dim rawData = Reporting.StreamToByteArray(Report)

            If PathFront IsNot Nothing Then File.Delete(PathFront)
            If PathBack IsNot Nothing Then File.Delete(PathBack)

            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()

                Dim cmdSave = "
                    UPDATE web_DriverApplicationPdf SET pageTitle=@pageTitle, pdfData=@pdfData, pdfDataSize=@pdfDataSize
                    WHERE appId=@appId AND pageFileName=@pageFileName;
                    IF @@ROWCOUNT = 0 BEGIN
                        INSERT INTO web_DriverApplicationPdf (appId, pageTitle, pageFileName, pdfData, pdfDataSize)
                        VALUES (@appId, @pageTitle, @pageFileName, @pdfData, @pdfDataSize);
                    END"
                Dim cmd As New SqlCommand(cmdSave, connection)
                cmd.Parameters.AddWithValue("appId", Master.app.id)
                cmd.Parameters.AddWithValue("pageTitle", Master.CurrentTitle)
                cmd.Parameters.AddWithValue("pageFileName", Master.CurrentPage)
                cmd.Parameters.AddWithValue("pdfData", rawData)
                cmd.Parameters.AddWithValue("pdfDataSize", rawData.Length)
                cmd.ExecuteNonQuery()

            End Using

        End Using
    End Sub

End Class