Imports System.Data.SqlClient
Imports System.IO.Compression
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports System.IO
Imports System.Threading
Imports Logic.DateExtensions

Public Class EditVehicle
    Inherits System.Web.UI.Page

    Property contractId As Integer
    Property vehicleId As Integer

    Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            
            vehicleId = Logic.Conversion.ToInteger(Request.Params("id"))

            ' Set contractId
            If vehicleId = 0 Then
                contractId = Logic.Conversion.ToInteger(Request.Params("cid"))
            Else
                Using connection As New SqlConnection(Logic.Database.connectionString)
                    connection.Open()
                    Dim cmd As New SqlCommand("SELECT ContractId FROM Vehicle WHERE ID=@vehicleId", connection)
                    cmd.Parameters.AddWithValue("vehicleId", vehicleId)
                    contractId = cmd.ExecuteScalar()
                End Using
            End If
            Master.CurrentClient.VerifyContractAccess(contractId)

            dsService.ConnectionString = Logic.Database.connectionString
            dsService.SelectParameters("contractId").DefaultValue = contractId
            dsService.SelectParameters("vehicleId").DefaultValue = vehicleId

            Dim perms = Master.CurrentClient.Permissions
            If perms.Contains("Document Export") Then
                btnDownloadAll.Visible = True
            Else
                btnDownloadAll.Visible = False
            End If
            If Not perms.Contains("View Vehicles Page") Then Throw New HttpException(403, "Forbidden")
            If Not perms.Contains("View Document Edit Page") Then
                Dim colCount = gvDocs.Columns.Count
                gvDocs.Columns(colCount - 2).Visible = False
            End If
            If Not perms.Contains("View Document Upload Page") Then
                btnUploadDoc.Visible = False
            End If

            dsDocs.ConnectionString = Logic.Database.ConnectionString
            If vehicleId > 0 Then
                dsDocs.SelectParameters("ItemId").DefaultValue = vehicleId
            Else
                dsDocs.SelectParameters("ItemId").DefaultValue = -1
            End If
            dsDocs.SelectParameters("CatID").DefaultValue = 9

            If Not Page.IsPostBack Then
                Master.SetParentPage("Vehicles.aspx?cid=" & contractId)
                _FillUI()
                _UpdatePermissions()
                _FillData(vehicleId)
            End If

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

    Private Sub btnAdd_Click() Handles btnAdd.Click
        Response.Redirect("EditServiceItem.aspx?vid=" & vehicleId & "&cid=" & contractId)
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Response.Redirect("Vehicles.aspx?cid=" & contractId)
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        If Not Page.IsValid Then
            Exit Sub
        End If

        Try

            Dim username = "[Web: " & Master.CurrentClient.username & "]"

            Dim vehicle = If(vehicleId, New Logic.Vehicle(vehicleId), New Logic.Vehicle())
            If vehicle.id = 0 Then
                vehicle.contractID = contractId
            ElseIf vehicle.contractID <> contractId Then
                Response.Redirect("Vehicles.aspx?cid=" & contractId)
            End If

            _GetData(vehicle)
            vehicle.Save(modifiedBy:=username)

            Response.Redirect("Vehicles.aspx?cid=" & contractId)

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

    Private Sub gvService_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvService.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim data As DataRowView = e.Row.DataItem
            Dim url = String.Format("EditServiceItem.aspx?id={0}&cid={1}", data("id"), data("contractId"))
            e.Row.Attributes.Add("data-href", url)
        End If
    End Sub

    Private Sub valType_ServerValidate(sender As Object, e As ServerValidateEventArgs) Handles valType.ServerValidate
        e.IsValid = (ddlType.SelectedValue <> 0)
    End Sub


    Private Sub _FillData(vehicleId As Integer)

        ddlMake.Items.AddRange(
            {New ListItem("", 0)}.Concat(
                From make In Logic.VehicleMake.List()
                Select New ListItem(make.Value, make.Key)
            ).ToArray())
        ddlType.Items.AddRange(
            {New ListItem("", 0)}.Concat(
                From type In Logic.VehicleType.ListActive()
                Select New ListItem(type.Value, type.Key)
            ).ToArray())

        Dim vehicle = If(vehicleId, New Logic.Vehicle(vehicleId), New Logic.Vehicle())
        With vehicle
            ddlMake.SelectedValue = .makeID
            txtModel.Text = .model
            ddlType.SelectedValue = .typeID
            txtUnit.Text = .unit
            txtUnitYear.Text = .unitYear
            txtVin.Text = .vin
            txtTagNumber.Text = .tagNumber
            dtTagExpires.Text = .tagExpiration.FormatForHtml5()
            ddlTireSize.SelectedValue = .tireSizeID
            dtPAIDue.Text = .paiDue.FormatForHtml5()
            chkOutOfService.Checked = .notInService
            dtOutOfService.Text = .notInServiceDate.FormatForHtml5()
            chkSuspended.Checked = .suspended
            dtSuspended.Text = .suspendedDate.FormatForHtml5()
            chkOtherDate.Checked = .otherDateEnabled
            txtOtherDate.Text = .otherDateDesc
            dtOtherDate.Text = .otherDate.FormatForHtml5()
            ddlDedicatedDriver.SelectedValue = .dedicatedDriverID
            txtGvwr.Text = .gvwr
            ddlOwnedLeased.Text = .ownedLeased
            txtLocation.Text = .location
            txtNotes.Text = .notes
            lstSchedules.Items.Clear()
            For Each item In .availableMaintenanceSchedules
                Dim li As New ListItem(item.Value, item.Key)
                If .selectedMaintenanceScheduleIds.Contains(item.Key) Then
                    li.Selected = True
                End If
                lstSchedules.Items.Add(li)
            Next
        End With

        If vehicle.makeID = 0 And vehicle.id > 0 Then
            ddlMake.Items.Add(New ListItem(vehicle.make, -1))
            ddlMake.SelectedValue = -1
        End If

        If Not String.IsNullOrEmpty(vehicle.unit) And Not IsNumeric(vehicle.unitYear) Then
            txtUnitYear.TextMode = TextBoxMode.SingleLine
            txtUnitYear.Text = vehicle.unitYear
        End If

    End Sub

    Private Sub _FillUI()

        ddlDedicatedDriver.Items.Clear()
        ddlDedicatedDriver.Items.AddRange(
            {New ListItem("", 0)}.Concat(
                From driver In Logic.Driver.ListForContract(contractId)
                Select New ListItem(driver.Value, driver.Key)
            ).ToArray())

        ddlTireSize.Items.Clear()
        ddlTireSize.Items.AddRange(
            {New ListItem("", 0)}.Concat(
                From tireSize in Logic.VehicleTireSize.List()
                Select New ListItem(tireSize.Value, tireSize.Key)
            ).ToArray())

    End Sub

    Private Sub _GetData(vehicle As Logic.Vehicle)
        Dim perms = Master.CurrentClient.Permissions
        With vehicle
            .makeID = If(ddlMake.SelectedValue > 0, ddlMake.SelectedValue, 0)
            .make = ddlMake.SelectedItem.Text
            .model = txtModel.Text
            .typeID = ddlType.SelectedValue
            .unit = txtUnit.Text
            .unitYear = txtUnitYear.Text
            .vin = txtVin.Text
            .tagNumber = txtTagNumber.Text
            .tireSizeID = ddlTireSize.SelectedValue
            .dedicatedDriverID = ddlDedicatedDriver.SelectedValue
            .gvwr = CDbl(txtGvwr.Text)
            .ownedLeased = ddlOwnedLeased.Text
            .location = txtLocation.Text
            .notes = txtNotes.Text

            If perms.Contains("Edit Vehicle Expirations") Then
                .tagExpiration = Logic.Conversion.ToDate(dtTagExpires.Text).Clip()
                .paiDue = Logic.Conversion.ToDate(dtPAIDue.Text).Clip()
                .notInService = chkOutOfService.Checked
                .notInServiceDate = Logic.Conversion.ToDate(dtOutOfService.Text).Clip()
                .suspended = chkSuspended.Checked
                .suspendedDate = Logic.Conversion.ToDate(dtSuspended.Text).Clip()
            End If
            If perms.Contains("Edit Vehicle Other Date") Then
                .otherDateEnabled = chkOtherDate.Checked
                .otherDateDesc = txtOtherDate.Text
                .otherDate = Logic.Conversion.ToDate(txtOtherDate.Text).Clip()
            End If

            Dim ids As New List(Of Integer)
            For Each item As ListItem In lstSchedules.Items
                If item.Selected Then ids.Add(item.Value)
            Next
            .selectedMaintenanceScheduleIds = ids

        End With
    End Sub

    Private Sub _UpdatePermissions()
        Dim perms = Master.CurrentClient.Permissions

        Dim permExpire = perms.Contains("Edit Vehicle Expirations")
        dtTagExpires.Enabled = permExpire
        dtPAIDue.Enabled = permExpire
        chkOutOfService.Enabled = permExpire
        dtOutOfService.Enabled = permExpire
        chkSuspended.Enabled = permExpire
        dtSuspended.Enabled = permExpire

        phSchedules.Visible = perms.Contains("Edit Vehicle Maintenance Schedules")

        phServiceItems.Visible = perms.Contains("Edit Vehicle Service Items")

        phOther.Visible = perms.Contains("Edit Driver Other Date")

    End Sub

    Protected Sub btnUploadDoc_Click(sender As Object, e As EventArgs) Handles btnUploadDoc.Click
        Try
            If vehicleId <> 0 Then
                Response.Redirect("DocumentsUploads.aspx?cid=" & contractId & "&ItemID=" & vehicleId & "&ctx=Vehicle")
            End If
        Catch ex As ThreadAbortException
            Throw
        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try
    End Sub

    Protected Sub btnDownloadAll_Click(sender As Object, e As EventArgs) Handles btnDownloadAll.Click
        DownloadFiles(contractId, 9, "Vehicle", vehicleId)
    End Sub

    Private Sub DownloadFiles(ByVal ContractID As String, ByVal CatID As String, ByVal CategoryName As String, ByVal ItemID As String)
        Dim cmd As New System.Data.SqlClient.SqlCommand
        Dim cmd2 As New System.Data.SqlClient.SqlCommand
        Dim DR As System.Data.SqlClient.SqlDataReader
        Dim DR2 As System.Data.SqlClient.SqlDataReader
        Dim connection As New SqlConnection(Logic.Database.ConnectionString)
        Dim Docconnection As New SqlConnection(Logic.Database.DocumentMannagerConnectionString(""))
        Dim FileName As String
        Dim sql As String = ""
        Dim FolderSubCatName As String

        Try
            Dim SourceFolder As String = HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID)
            Dim DestFile As String = HttpContext.Current.Server.MapPath("~/Exports/" & CategoryName & "-" & ItemID & ".zip")

            If System.IO.File.Exists(DestFile) Then
                System.IO.File.Delete(DestFile)
            End If
            If System.IO.Directory.Exists(SourceFolder) Then
                System.IO.Directory.Delete(SourceFolder, True)
            End If
            If System.IO.File.Exists(DestFile) Then
                System.IO.File.Delete(DestFile)
            End If

            connection.Open()
            cmd.Connection = connection

            sql = "SELECT DocumentsNew.ID AS DocID,DocumentsNew.DocName,ISNULL(DocumentCatagoriesNew.Name,'No Category') AS Cat,ISNULL(DocumentsSubCategory.Name,'No Category') AS SubCat,DocumentsNew.FileType, 
                ISNULL(CASE 
                WHEN DocumentsNew.CategoryId=1 AND ISNULL(DocumentsNew.ItemID,0)>0 THEN ISNULL(Accident.DriverName,'') + '  -  ' + FORMAT(Accident.AccidentDate,'yyyy/MM/dd')
                When DocumentsNew.CategoryId=2 Then 'NO ITEMS'
                WHEN DocumentsNew.CategoryId=3 AND ISNULL(DocumentsNew.ItemID,0)>0 THEN Driver.LastName + ', ' + Driver.FirstName + ' ' + Driver.MiddleName + ' ' + Driver.Suffix 
                When DocumentsNew.CategoryId=4 AND ISNULL(DocumentsNew.ItemID,0)>0 Then ISNULL(DrugAlcoholTest.DriverName,'') + ' - ' + FORMAT(DrugAlcoholTest.TestDate,'yyyy/MM/dd') + ' - ' + ISNULL(DrugAlcoholTestType.Name,'')
                WHEN DocumentsNew.CategoryId=5 THEN 'NO ITEMS'
                When DocumentsNew.CategoryId=6 AND ISNULL(DocumentsNew.ItemID,0)>0 Then RegistrationDocType.Name + ' - ' + CAST(RegistrationDoc.ID AS VARCHAR)
                WHEN DocumentsNew.CategoryId=7 AND ISNULL(DocumentsNew.ItemID,0)>0 THEN RoadsideInspection.DriverName + ' - ' + FORMAT(RoadsideInspection.InspectionDate,'yyyy/MM/dd') + ' - ' + RoadsideInspection.Vehicle1Desc 
                When DocumentsNew.CategoryId=8 AND ISNULL(DocumentsNew.ItemID,0)>0 Then ISNULL(TrainingTopic.Name,'') + ' - ' + ISNULL(Training.DriverName,'')
                WHEN DocumentsNew.CategoryId=9 AND ISNULL(DocumentsNew.ItemID,0)>0 THEN Vehicle.Unit + ' - ' + Vehicle.UnitYear + ' - ' + Vehicle.Make + ' - ' + Vehicle.Model
                Else 'NO ITEMS'
                END,'') AS ItemDesc 
                FROM DocumentsNew 
                LEFT JOIN DocumentCatagoriesNew ON DocumentsNew.CategoryID=DocumentCatagoriesNew.id
                LEFT JOIN DocumentsSubCategory ON DocumentsNew.SubCategoryID=DocumentsSubCategory.ID 
                LEFT JOIN Accident ON DocumentsNew.ItemID=Accident.ID AND DocumentsNew.CategoryID=1
                LEFT JOIN Driver On DocumentsNew.ItemID=Driver.ID And DocumentsNew.CategoryID=3
                LEFT JOIN DrugAlcoholTest ON DocumentsNew.ItemID=DrugAlcoholTest.ID AND DocumentsNew.CategoryID=4 LEFT JOIN DrugAlcoholTestType ON DrugAlcoholTest.TestTypeID=DrugAlcoholTestType.ID
                LEFT JOIN RegistrationDoc On DocumentsNew.ItemID=RegistrationDoc.ID And DocumentsNew.CategoryID=6 LEFT JOIN RegistrationDocType On TypeID = RegistrationDocType.ID
                LEFT JOIN RoadsideInspection ON DocumentsNew.ItemID=RoadsideInspection.ID AND DocumentsNew.CategoryID=7
                LEFT JOIN Training On DocumentsNew.ItemID=Training.ID And DocumentsNew.CategoryID=8 LEFT JOIN TrainingTopic On TopicID = TrainingTopic.ID
                LEFT JOIN Vehicle ON DocumentsNew.ItemID=Vehicle.ID AND DocumentsNew.CategoryID=9

                WHERE DocumentsNew.ContractID=@ContractID
                AND (@CatID=0 OR DocumentsNew.CategoryID=@CatID)
                AND (@ItemID=0 OR DocumentsNew.ItemID=@ItemID)

                ORDER BY ISNULL(DocumentCatagoriesNew.Name,'No Category'),ISNULL(DocumentsSubCategory.Name,'No Category'),DocName,DocumentsNew.ID"

            cmd.CommandText = sql
            cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ContractID", SqlDbType.BigInt)).Value = ContractID
            cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@CatID", SqlDbType.BigInt)).Value = CatID
            cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ItemID", SqlDbType.BigInt)).Value = ItemID

            cmd2.CommandText = "Select * FROM Documents WHERE DocumentID=@DocID"
            cmd2.Parameters.Add(New System.Data.SqlClient.SqlParameter("@DocID", SqlDbType.BigInt)).Value = 0

            DR = cmd.ExecuteReader
            While DR.Read
                'FolderCatName = Trim(DR("Cat").Replace("&", "-").Replace(",", "_").Replace(".", "_").Replace("/", "_").Replace("\", "_"))
                'FolderItemName = Trim(DR("ItemDesc").Replace("&", "-").Replace(",", "_").Replace(".", "_").Replace("/", "_").Replace("\", "_"))
                FolderSubCatName = Trim(DR("SubCat").Replace("&", "-").Replace(",", "_").Replace(".", "_").Replace("/", "_").Replace("\", "_").Replace("'", ""))

                'see if sub folder exists
                If Not System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & FolderSubCatName)) Then
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & FolderSubCatName))
                End If

                'save each file
                If InStr(DR("DocName"), ".") > 1 Then
                    FileName = HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & FolderSubCatName & "/" & DR("DocName"))
                Else
                    FileName = HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & FolderSubCatName & "/" & DR("DocName") & "." & DR("FileType"))
                End If
                Docconnection = New SqlConnection(Logic.Database.DocumentMannagerConnectionString(DR("Cat")))
                Docconnection.Open()
                cmd2.Connection = Docconnection

                cmd2.Parameters("@DocID").Value = (DR("DocID"))
                DR2 = cmd2.ExecuteReader
                If DR2.Read Then
                    'load from correct db
                    Dim buffer() As Byte = DR2("DocBlob")
                    Dim newStream As New System.IO.MemoryStream(buffer)
                    Dim f As New System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
                    newStream.WriteTo(f)
                    f.Close()
                    newStream.Close()
                    buffer = Nothing
                    newStream = Nothing
                End If
                DR2.Close()
                Docconnection.Close()
            End While
            DR.Close()

            ''save application if exists
            If (CatID = 3) Then
                Using outPdf As New PdfDocument()
                    cmd.CommandText = " Select Driver.ID, Driver.LastName + ', ' + Driver.FirstName + ' ' + Driver.MiddleName + ' ' + Driver.Suffix AS ItemName,pdf.pdfData 
                        FROM Driver LEFT JOIN web_DriverApplication app On Driver.webAppID=app.ID LEFT JOIN web_DriverApplicationPDF pdf On app.id=pdf.appId 
                        WHERE Not pageFileName Like '%/%' AND Driver.ContractID=@ContractID AND (@ItemID=0 OR Driver.ID=@ItemID) ORDER BY Driver.ID,pdf.id"
                    DR = cmd.ExecuteReader()
                    While DR.Read()
                        Using ms As New MemoryStream(DirectCast(DR("pdfData"), Byte()))
                            Using inPdf = PdfReader.Open(ms, PdfDocumentOpenMode.Import)
                                For i = 0 To inPdf.PageCount - 1
                                    outPdf.AddPage(inPdf.Pages(i))
                                Next
                                'inPdf.Close()
                            End Using
                        End Using

                    End While
                    DR.Close()
                    If outPdf.PageCount > 0 Then
                        'see if sub folder exists
                        If Not System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & "Web Application")) Then
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/" & "Web Application"))
                        End If
                        FileName = HttpContext.Current.Server.MapPath("~/Exports/" & ContractID & "/" & CategoryName & "/" & ItemID & "/Web Application/AllAppDocs-" & ItemID & ".pdf")
                        outPdf.Save(FileName)
                    End If
                End Using
            End If

            ZipFile.CreateFromDirectory(SourceFolder, DestFile, CompressionLevel.Optimal, True)

            With Response
                .Buffer = True
                .Charset = ""
                .Cache.SetCacheability(HttpCacheability.NoCache)
                .ContentType = "application/zip"
                .AddHeader("content-disposition", "inline;filename=CAMS_" & CategoryName & "_" & ItemID & ".zip")
                '.BinaryWrite(doc.Data)
                .WriteFile(DestFile)
                .Flush()
                .End()
            End With
        Catch ex As Exception
            '            Me.HandleException("An Error Occurred while Exporting Documents", ex)
        Finally
            connection.Close()
            Docconnection.Close()

        End Try
    End Sub

End Class