' SummaryPage2_SecurityEnquiryReport_PPSRNZ
Option Explicit On
Option Strict On

' #################################################################
' PPSR NZ Security Report Summary Page Script
'
' Version: 1.01 (27/03/2024)
'
' Usage: Security Enquiry form and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.01  27/03/2024  ISS      J033194   Improved handling for diacritics
' #################################################################

'#Const "OutOfDateWarningDays",Integer,30,"Number of days before warning the Enquiry is out-of-date."

' Constants
Private OutOfDateWarningDays As Integer = 30

' Special Constants
Const TestMode As Boolean = False

Public Function Main(source As Object,
                     eventId As String,
                     eventArgs As ISKeyValueList,
                     ByRef handled As Boolean,
                     ByRef returnValues As ISKeyValueList,
                     ByRef text As String) As Boolean

  Dim i As Integer
  Dim Response As ISSecurityEnquiryResponse
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    OutOfDateWarningDays = .GetInteger("OutOfDateWarningDays", OutOfDateWarningDays)
  End With

  ' Get Security Enquiry Service Logs (ignoring any errors)
  If Main Then
    Try
      Main = finBL.SecurityEnquiry.GetSecurityEnquiryServiceLogs(CInt(source), ServiceLogs)
    Catch ex As Exception
      finBL.Error.ErrorBeginFromException(ex)
      Return False
    End Try
  End If

  If Main Then
    If ServiceLogs.Count = 0 Then
      ' Error
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log for a Security Enquiry.")
    Else
      For i = ServiceLogs.Count - 1 To 0 Step - 1
        If ServiceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
          ServiceLog = ServiceLogs(i)
          Response = DirectCast(ServiceLogs(i).ExResponse, ISSecurityEnquiryResponse)
          Exit For
        End If
      Next
      If Response Is Nothing Then
        ' Error
        Main = False
        finBL.Error.ErrorBegin("Invalid Service Log for a Security Enquiry.")
      End If
    End If
  End If

  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return main page content
        Main = CreatePage(ServiceLog, Response, text)
    End Select
  End If

End Function

Private Function CreatePage(serviceLog As ISServiceLog,
                            response As ISSecurityEnquiryResponse,
                            ByRef html As String) As Boolean

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With HtmlSummaryPage2StringBuilder
    ' Display test watermark
    If serviceLog.TestMode Then .Watermark = "Test Mode"

    ' Note: Embed images (will also embed CSS) since we want to be able to easily produce a PDF document
    .Initialise(ScriptInfo, False, True)

    ' Begin HTML Header
    .HtmlHeaderBegin(String.Format("{0} {1}", response.ServiceName, response.ProductId), isefinSummaryPageStyle.ServiceReport)

    ' Theme
    .HtmlHeaderInsertServiceReportTheme("#3E4D5D", "#75BFDD", "#FFFFFF", "#D3E9F4")

    ' Intersoft PDF Options (including style tweaks)
    .HtmlHeaderInsertPdfGenerationHints("A4", "Portrait", 880, "1.5cm", "1.5cm", "1cm", "1cm", "font-size:0.9em")

    ' Finalise HTML Header
    .HtmlHeaderEnd()
  End With

  ' VedaScore Apply
  Select Case TypeName(response)
    Case "ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData"
      Me.CreatePage_PPSRNZ_GetVehicleData(ServiceLog, Response, HtmlSummaryPage2StringBuilder)
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.Append("<hr/>")
  HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|This report was produced by finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using information retrieved from the " & response.ServiceName & " service on " & finBL.FormatDateTime(response.EnquiryDate, True, True, True) &"}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

Private Sub CreatePage_PPSRNZ_GetVehicleData(serviceLog As ISServiceLog,
                                             response As ISSecurityEnquiryResponse,
                                             sb As finHtmlSummaryPage2StringBuilder)

  Dim PPSRNZResponse As ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finbl.CreateSummaryTables()
  PPSRNZResponse = DirectCast(response, ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData)

  With sb
    ' Heading
    .AppendH1(PPSRNZResponse.VehicleDescription)
    .AppendH2(String.Format("{0} - {1}", PPSRNZResponse.ProductId, PPSRNZResponse.ServiceName))

    .SummaryTablesAppend(Me.PPSRNZ_GetVehicleData_InformationProvided(PPSRNZResponse))
    .SummaryTablesAppend(Me.PPSRNZ_GetVehicleData_VehicleDescription(PPSRNZResponse))
    .SummaryTablesAppend(Me.PPSRNZ_GetVehicleData_Alerts(PPSRNZResponse))
  End With

End Sub

Private Function PPSRNZ_GetVehicleData_InformationProvided(PPSRNZResponse As ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData) As ISSummaryTables

  Dim Days As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

    ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Main
  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "InformationProvided", 3, 16, 40, TestMode)
  With SummaryTable
    Days = CInt(DateDiff(DateInterval.Day, PPSRNZResponse.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    If Days > OutOfDateWarningDays Then
      With .Rows.Add.Cells
        .AddCaption("Enquiry Date:")
        .AddWiki("**" & finBL.FormatDateTime(PPSRNZResponse.EnquiryDate, True) & " --This Report is " & CStr(Days) & " days old.--**").CellClass = iseSummaryTableCellClass.WarningBold
      End With
    Else
      .AddRowCaptionDateTime("Enquiry Date:", PPSRNZResponse.EnquiryDate)
    End If
    If Len(PPSRNZResponse.Request.RegistrationPlate) = 0 Then
      .AddRowCaptionWiki("Plate Number:", "**Plate Number not supplied**")
    Else
      .AddRowCaptionWiki("Plate Number:", String.Format("**++{0}++**", PPSRNZResponse.Request.RegistrationPlateResolved))
    End If
    If Len(PPSRNZResponse.Request.Vin) = 0 Then
      .AddRowCaptionWiki("VIN:", "**VIN not supplied**")
    Else
      .AddRowCaptionWiki("VIN:", String.Format("**++{0}++**", PPSRNZResponse.Request.Vin))
    End If
  End With
  SummaryTables.Add("InformationProvider", SummaryTable)

  Return SummaryTables

End Function

Private Function PPSRNZ_GetVehicleData_Alerts(PPSRNZResponse As ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData) As ISSummaryTables

  Dim Days As Integer
  Dim Warnings As finWarnings
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Warnings
  Warnings = finBL.CreateWarnings()

  ' Build Warning Lists
  With PPSRNZResponse
    ' Out of Date
    Days = CInt(DateDiff(DateInterval.Day, .EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    If Days > OutOfDateWarningDays Then
      Warnings.AddWarning(String.Format("This is an OLD Report, data is from {0} days ago.", Days),,, isefinWarningLevel.Critical)
    End If
  End With

  ' Add Alerts
  If Warnings.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Alerts", "Alerts", 2)
    SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()
    SummaryTables.Add("Alerts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function PPSRNZ_GetVehicleData_VehicleDescription(PPSRNZResponse As ISSecurityEnquiryResponse_PPSRNZ_GetVehicleData) As ISSummaryTables

  Dim VehicleYear As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

    ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Main
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Vehicle Description", "VehicleDescription", 2, 16, 40, TestMode)
  With SummaryTable
    ' Year
    If PPSRNZResponse.Year <> 0 Then
      VehicleYear = CStr(PPSRNZResponse.Year)
    Else
      VehicleYear = ""
    End If

    .AddRowCaptionText("Plate Number:", PPSRNZResponse.RegistrationPlate, True)
    .AddRowCaptionText("VIN:", PPSRNZResponse.Vin, True)
    .AddRowCaptionText("Vehicle Year:", VehicleYear, True)
    .AddRowCaptionText("Make:", PPSRNZResponse.Make, True)
    .AddRowCaptionText("Model:", PPSRNZResponse.Model, True)
    .AddRowCaptionText("Colour:", PPSRNZResponse.Colour)
  End With
  SummaryTables.Add("VehicleDescription", SummaryTable)

  Return SummaryTables

End Function