'SummaryPage2_SearchFsResponse_ItemSummary_AU
Option Explicit On
Option Strict On

' #################################################################
' PPSR B2G AU Financing Statement Search Result
'
' Add the following text to KB articles related to this script:
' Note: This summary page is not currently accessible for customisation.
'
' Version: 1.01 (17/09/2021)
'
' Usage: PPSR B2G (AU) Search Results.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  14/05/2021  ISS                Created
'    1.01  17/09/2021  ISS      J027414   Moved NEVDIS Verification to own block
' #################################################################

' Objects
Private mEventArgs As ISKeyValueList
Private mSearchFsResponse As ISG2BSearchFsResponse
Private mSearchFsResponseSummaryItem As ISG2BSearchFsResponseSummaryItem

' Other
Private FormKey As String
Private FormPageKey As String
Private FormTabKey As String
Private mIndex As Integer

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

  ' Assume Success
  Main = True

  ' Get Form Information
  FormKey = ScriptInfo.FormKey
  FormPageKey = ScriptInfo.FormPageKey
  FormTabKey = ScriptInfo.FormTabKey

  ' Initialise
  mEventArgs = eventArgs
  mIndex = mEventArgs.GetInteger("Index")
  mSearchFsResponse = DirectCast(source, ISG2BSearchFsResponse)

  ' Override Index
  If mIndex <> -1 AndAlso mSearchFsResponse.Count = 0 Then
    mIndex = -1
  End If

  ' Set Item
  If mIndex >= 0 AndAlso mIndex < mSearchFsResponse.Count Then
    mSearchFsResponseSummaryItem = mSearchFsResponse(mIndex)
  End If

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main Event, i.e., Return main page content
      Main = GetPage(text)
  End Select

End Function

Public Function GetPage(ByRef html As String) As Boolean

  Dim Ok As Boolean
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim RegistrationSummary As ISSummaryTables
  Dim ShowOtherDetails As Boolean

  ' Assume Success
  Ok = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("SearchFsResponseAU", isefinSummaryPageStyle.Blocks)
    .HtmlHeaderEnd()
  End With

  If mIndex = -1 Then
    ' Registrations not found but display Search Request details.
    ' Section Begin
    sb.SectionColumnsBegin("100%")

    ' Column Begin
    sb.ColumnBegin("100%")

    ' Block
    sb.BlockBegin("Summary",, isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTablesAppend(GetSummary())
    sb.BlockEnd()

    ' NEVDIS Verification
    If mSearchFsResponse.MotorVehicleVerificationStatus <> iseSecurityRegisterIdentifierVerificationStatus.NotPerformed Then
      sb.BlockBegin("NEVDIS Verification")
      sb.SummaryTablesAppend(GetNevdisVerification())
      sb.BlockEnd()
    End If

    ' End Column
    sb.ColumnEnd()

    ' Section End
    sb.SectionColumnsEnd()
  Else
    ' Get Registration Summary
    RegistrationSummary = GetRegistrationSummary(ShowOtherDetails)

    ' Section Begin
    sb.SectionColumnsBegin("100%")

    ' Column Begin
    If ShowOtherDetails Then
      sb.ColumnBegin("50%")
    Else
      sb.ColumnBegin("100%")
    End If

    ' Summary Block
    sb.BlockBegin("Summary", "", isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTablesAppend(GetSummary())
    sb.BlockEnd()

    ' Registration Summary
    sb.BlockBegin("Registration Summary")
    sb.SummaryTablesAppend(RegistrationSummary)
    sb.BlockEnd()

    ' NEVDIS Verification
    If mSearchFsResponse.MotorVehicleVerificationStatus <> iseSecurityRegisterIdentifierVerificationStatus.NotPerformed Then
      sb.BlockBegin("NEVDIS Verification")
      sb.SummaryTablesAppend(GetNevdisVerification())
      sb.BlockEnd()
    End If

    ' End Column
    sb.ColumnEnd()

    ' Other Details
    If ShowOtherDetails Then
      ' Column Begin
      sb.ColumnBegin("50%")

      ' Collateral
      sb.BlockBegin("Collateral")
      sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.SecurityStmt_SecurityRegisterAUCollateralItemSummary(ScriptInfo, mSearchFsResponseSummaryItem.FinancingStatement))
      sb.BlockEnd()

      ' Grantors
      sb.BlockBegin("Grantors")
      sb.SummaryTablesAppend(GetGrantorSummary())
      sb.BlockEnd()

      ' Secured Party Groups
      sb.BlockBegin("Secured Party Groups")
      sb.SummaryTablesAppend(GetSecuredPartyGroupSummary())
      sb.BlockEnd()

      ' End Column
      sb.ColumnEnd()
    End If

    ' Section End
    sb.SectionColumnsEnd()
  End If

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Ok

End Function

''' <summary>
'''  Retrives the Grantor Summary.
''' </summary>
Private Function GetGrantorSummary() As ISSummaryTables

  Dim Debtor As ISFinancingStatementDebtor
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim IndividualGrantorCount As Integer
  Dim Information As String

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Configure Summary Table
  SummaryTable.TableClass = iseSummaryTableClass.Information

  ' Columns
  With SummaryTable.Columns
    .AddText(12).NoBreakChars = 22
    .AddText()
  End With

  ' Grantors
  With mSearchFsResponseSummaryItem.FinancingStatement
    If .Debtors.Count = 0 Then
      Information = "{{INFO|No Grantor applicable for this registration.}}"
    Else
      ' Debtors
      For Each Debtor In .Debtors
        ' Heading
        If .Debtors.Count <> 1 Then
          SummaryTable.Rows.AddSectionHeading2("Debtor " & .Debtors.IndexOf(Debtor) + 1)
        End If

        ' Type
        With Debtor
          If .IsOrganisation Then
            SummaryTable.AddRowCaptionText("Organisation?:", "Yes")
            Select Case .OrganisationType
              Case "ARSN", "ACN", "ARBN"
                SummaryTable.AddRowCaptionText(.OrganisationType & ":", .CompanyNumber)
                If Len(.OrganisationName) <> 0 Then SummaryTable.AddRowCaptionText("Organisation Name:", .OrganisationName)

              Case "ABN"
                SummaryTable.AddRowCaptionText("ABN:", .BusinessNumber)
                If Len(.OrganisationName) <> 0 Then SummaryTable.AddRowCaptionText("Organisation Name:", .OrganisationName)

              Case Else
                SummaryTable.AddRowCaptionText("Organisation Name:", .OrganisationName)
            End Select
          Else
            IndividualGrantorCount += 1
            SummaryTable.AddRowCaptionText("Organisation?:", "No")
            SummaryTable.AddRowCaptionText("Name:", finBL.Runtime.TextUtilities.ListSeparate(" ", .FirstName, .LastName))
          End If
        End With
      Next

      ' Individual Grantor Count
      If IndividualGrantorCount = 1 Then
        Information = "{{INFO|An Individual Grantor exists}}"
      ElseIf IndividualGrantorCount <> 0 Then
        Information = "{{INFO|" & IndividualGrantorCount & " Individual Grantors exist}}"
      End If
    End If
  End With

  ' Information
  If Len(Information) <> 0 Then
    SummaryTable.TextAfter = Information
  End If

  ' Add to Summary Tables
  SummaryTables.Add("GrantorSummary", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Get NEVDIS Verification.
'''  Display NEVDIS data even if no Registrations found so user can confirm they are searching on the correct Vehicle.
''' </summary>
Private Function GetNevdisVerification() As ISSummaryTables

  Dim CellClass As iseSummaryTableCellClass
  Dim MotorVehicleDetail As ISG2BSearchFsResponseMotorVehicleDetail
  Dim s As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  With SummaryTable
    .TableClass = iseSummaryTableClass.Information

    ' Columns
    With .Columns
      .AddText(25)
      .AddText()
    End With

    Select Case mSearchFsResponse.MotorVehicleVerificationStatus
      Case iseSecurityRegisterIdentifierVerificationStatus.Found
        CellClass = iseSummaryTableCellClass.PositiveBold
      Case Else
        CellClass = iseSummaryTableCellClass.NormalBold
    End Select
    .AddRowCaptionText("Verification Status:", mSearchFsResponse.MotorVehicleVerificationStatusText, True, CellClass)

    If mSearchFsResponse.MotorVehicleVerificationStatus = iseSecurityRegisterIdentifierVerificationStatus.Found Then
      For Each MotorVehicleDetail In mSearchFsResponse.MotorVehicleDetails
        Warnings = ""

        ' Heading
        .Rows.AddSectionHeading2("Vehicle " & mSearchFsResponse.MotorVehicleDetails.IndexOf(MotorVehicleDetail) + 1)

        ' Vehicle Type
        Select Case MotorVehicleDetail.VehicleIdType
          Case iseRegisterSerialNumberType.AU_MotorVehicle_Chassis
            .AddRowCaptionText("Chassis:", MotorVehicleDetail.Chassis)
          Case iseRegisterSerialNumberType.AU_MotorVehicle_VIN
            .AddRowCaptionText("VIN:", MotorVehicleDetail.VIN)
        End Select

        ' Registration
        If Len(MotorVehicleDetail.PlateNumber) <> 0 Then
          .AddRowCaptionText("Registration:", MotorVehicleDetail.PlateNumber)
        End If

        ' State
        If Len(MotorVehicleDetail.State) <> 0 Then
          .AddRowCaptionText("State:", MotorVehicleDetail.State)
          If Not MotorVehicleDetail.StateParticipation Then
            Warnings &= "{{Warning|The state or territory of the most recent vehicle registration recorded for the vehicle has not agreed to participate in providing vehicle and registration information for PPSR.}}"
          End If
        End If

        ' Other Motor Vehicle Details
        If Len(MotorVehicleDetail.EngineNumber) <> 0 Then .AddRowCaptionText("Engine Number:", MotorVehicleDetail.EngineNumber)
        If Len(MotorVehicleDetail.VehicleType) <> 0 Then .AddRowCaptionText("Vehicle Type:", MotorVehicleDetail.VehicleType)
        If Len(MotorVehicleDetail.BodyType) <> 0 Then .AddRowCaptionText("Body Style:", MotorVehicleDetail.BodyType)
        If Len(MotorVehicleDetail.Make) <> 0 Then .AddRowCaptionText("Make:", MotorVehicleDetail.Make)
        If Len(MotorVehicleDetail.Model) <> 0 Then .AddRowCaptionText("Model:", MotorVehicleDetail.Model)
        If Len(MotorVehicleDetail.Colour) <> 0 Then .AddRowCaptionText("Colour:", MotorVehicleDetail.Colour)
        If Len(MotorVehicleDetail.YearOfManufacture) <> 0 Then .AddRowCaptionText("Year:", MotorVehicleDetail.YearOfManufacture)
        If MotorVehicleDetail.DateRegistrationExpiry <> Nothing Then .AddRowCaptionDate("Registration Expires:", MotorVehicleDetail.DateRegistrationExpiry)
        If Len(MotorVehicleDetail.ComplianceYearMonth) <> 0 Then .AddRowCaptionText("Compliance Date:", MotorVehicleDetail.ComplianceYearMonth)

        ' Stolen
        For Each s In MotorVehicleDetail.StolenDetails
          .AddRowCaptionText("Stolen Summary " & MotorVehicleDetail.StolenDetails.IndexOf(s) + 1 & ":", s)
        Next
        If MotorVehicleDetail.StolenDetails.Count <> 0 Then
          Warnings &= "{{Warning|Stolen details exist.}}"
        End If

        ' Written Off
        For Each s In MotorVehicleDetail.WrittenOffDetails
          .AddRowCaptionText("Written off Summary " & MotorVehicleDetail.WrittenOffDetails.IndexOf(s) + 1 & ":", s)
        Next
        If MotorVehicleDetail.WrittenOffDetails.Count <> 0 Then
          Warnings &= "{{Warning|Written Off details exist.}}"
        End If

        ' Warnings
        If Len(Warnings) <> 0 Then
          .Rows.AddText(Warnings)
        End If
      Next
    End If
  End With

  ' Add to Summary Tables
  SummaryTables.Add("NEVDISVerificationSummary", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Retrives the Search Response Summary.
''' </summary>
Private Function GetRegistrationSummary(ByRef showDetails As Boolean) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise ByRef Parameters
  showDetails = False

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Configure Summary Table
  SummaryTable.TableClass = iseSummaryTableClass.Information

  ' Columns
  With SummaryTable.Columns
    .AddText(25)
    .AddText()
  End With

  ' Financing Statement
  If mSearchFsResponseSummaryItem IsNot Nothing Then
    With mSearchFsResponseSummaryItem.FinancingStatement
      ' Registration
      SummaryTable.AddRowCaptionWiki("Registration Number:", "**[[app://FormAction?action=ViewFinancingStatement&index=" & mIndex & "&serviceLogPk=" & mSearchFsResponse.ServiceLogPk & "|" & .FinancingStatementId & "]]**")

      ' Restriction Reason
      Select Case mSearchFsResponseSummaryItem.RestrictionReason
        Case iseSecurityRegisterRestrictionReason.AccessRestricted
          ' Access Restricted
          If .ExpiryDate <> Nothing Then SummaryTable.AddRowCaptionDate("Expires:", .ExpiryDate)
          Warnings &= "{{Warning|Access has been restricted to this Registration}}"

        Case iseSecurityRegisterRestrictionReason.Archived
          ' Archived
          Warnings &= "{{Warning|This Registration has been archived}}"

        Case iseSecurityRegisterRestrictionReason.Removed
          ' Removed
          Warnings &= "{{Warning|This Registration has been removed}}"

        Case Else
          ' Show other blocks
          showDetails = True

          ' General
          SummaryTable.AddRowCaptionText("Change Number:", CStr(.Version))
          SummaryTable.AddRowCaptionText("Registration Kind:", finBL.Runtime.TextUtilities.SplitWordsAtCapitals(.RegistrationKind))
          If Len(.RegistrationKind) <> 0 Then
            Warnings &= "{{Warning|" & "Registration Kind is " & finBL.Runtime.TextUtilities.SplitWordsAtCapitals(.RegistrationKind) & "}}"
          End If
          SummaryTable.AddRowCaptionDate("Registered:", .DateRegistered)
          SummaryTable.AddRowCaptionDate("Expires:", .ExpiryDate)
      End Select
    End With
  End If

  ' Warnings
  If Len(Warnings) <> 0 Then
    SummaryTable.TextAfter = Warnings
  End If

  ' Add to Summary Tables
  SummaryTables.Add("RegistrationSummary", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Retrives the Secured Party Group Summary.
''' </summary>
Private Function GetSecuredPartyGroupSummary() As ISSummaryTables

  Dim SecuredParty As ISSecuredParty
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Configure Summary Table
  SummaryTable.TableClass = iseSummaryTableClass.Information

  ' Columns
  With SummaryTable.Columns
    .AddText(12).NoBreakChars = 22
    .AddText()
  End With

  ' Secured Parties
  With mSearchFsResponseSummaryItem.FinancingStatement
    ' Secured Party Group
    If finBL.SecuredPartyGroups.ExistsSpgId(.SpgId) Then
      SummaryTable.AddRowCaptionCodeDescription("SPG:", .SpgId, finBL.SecuredPartyGroups)
    Else
      SummaryTable.AddRowCaptionText("SPG:", .SpgId)
    End If

    ' Secured Parties
    For Each SecuredParty In .SecuredParties
      ' Heading
      If .SecuredParties.Count <> 1 Then
        SummaryTable.Rows.AddSectionHeading2("Secured Party " & .SecuredParties.IndexOf(SecuredParty) + 1)
      End If

      ' Secured Party
      With SecuredParty
        If .SpgType = iseSecurityRegisterSecuredPartyGroupType.AddressForService Then
          ' Address for Service - physical address takes priority
          If Len(.PhysicalAddressCity) <> 0 OrElse Len(.PhysicalAddressState) <> 0 OrElse Len(.PhysicalAddressCountryCode) <> 0 Then
            SummaryTable.AddRowCaptionText("Location:", finBL.Runtime.TextUtilities.ListSeparate(", ", .PhysicalAddressCity, .PhysicalAddressState, IIf(.PhysicalAddressCountryCode = "AU", "", .PhysicalAddressCountryCode)))
          Else
            SummaryTable.AddRowCaptionText("Location:", finBL.Runtime.TextUtilities.ListSeparate(", ", .PostalAddressCity, .PostalAddressState, IIf(.PostalAddressCountryCode = "AU", "", .PostalAddressCountryCode)), True)
          End If
        Else
          ' Other Secured Party Group Types
          Select Case .SpgType
            Case iseSecurityRegisterSecuredPartyGroupType.Individual
              ' Individual
              SummaryTable.AddRowCaptionText("Name:", finBL.Runtime.TextUtilities.ListSeparate(" ", .FirstName, .LastName))

            Case iseSecurityRegisterSecuredPartyGroupType.Organisation
              ' Organisation
              If Len(.OrganisationNumberType) <> 0 Then
                SummaryTable.AddRowCaptionText(.OrganisationNumberType & ":", .OrganisationNumber)
              ElseIf Len(.OrganisationNumber) <> 0 Then
                SummaryTable.AddRowCaptionText("Organisation Number:", .OrganisationNumber)
              End If

              ' Name
              If Len(.OrganisationName) <> 0 Then
                SummaryTable.AddRowCaptionText("Organisation Name:", .OrganisationName)
              End If
          End Select
        End If
      End With
    Next
  End With

  ' Add to Summary Tables
  SummaryTables.Add("RegistrationSummary", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Retrives the Search Response Summary.
''' </summary>
Private Function GetSummary() As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPk As Integer
  Dim Warnings As String

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Get User Pk
  UserPk = mEventArgs.GetInteger("UserPk")

  ' Summary
  With SummaryTable
    .TableClass = iseSummaryTableClass.Information

    ' Columns
    With .Columns
      .AddText(25)
      .AddText()
    End With

    ' Search Criteria
    .AddRowCaptionText("Search Number:", mSearchFsResponse.SearchId)
    .AddRowCaptionText("Search Type:", mEventArgs.GetString("SearchType"))
    .AddRowCaptionText("Criteria:", mEventArgs.GetString("SearchCriteria"))
    .AddRowCaptionText("Billing Number:", mSearchFsResponse.BillingTxnNumber)

    ' Extra information displayed for Previous Searches
    If UserPk <> 0 AndAlso finBL.Users.ExistsPk(UserPk) Then
      .AddRowCaptionDateTime("Date:", mEventArgs.GetDate("Date"))
      .AddRowCaptionCodeDescription("User:", UserPk, finBL.Users)
    End If

    ' Warnings
    If mSearchFsResponse.Count = 0 Then
      warnings &= "{{Warning| No Registrations were found on the PPSR for the entered Search Criteria.}}"
    ElseIf mSearchFsResponse.AccessToSearchResultExpiryTime <> Nothing AndAlso mSearchFsResponse.AccessToSearchResultExpiryTime > finBL.TimeZoneFunctions.GetCurrentTimeZoneDateTime("2780").AddDays(-1) Then
      warnings &= "{{info|" & String.Format("NOTE: The search result access period expires on {0} (Canberra time)", finBL.FormatDateTime(mSearchFsResponse.AccessToSearchResultExpiryTime, True)) & "}}"
    End If

    If Len(mSearchFsResponse.TransitionalPeriodMessage) <> 0 Then
      Warnings &= "{{Warning|" & mSearchFsResponse.TransitionalPeriodMessage & "}}"
    End If

    ' Warnings
    If Len(Warnings) <> 0 Then
      .TextAfter = Warnings
    End If
  End With

  ' Add to Summary Tables
  SummaryTables.Add("Summary", SummaryTable)

  Return SummaryTables

End Function