' SummaryPage2_AccountInstalments_InstalmentSummary
Option Explicit On
Option Strict On

' #################################################################
' Used to pick an Instalment value for a Loan Account
' 
' Version: 2.01 (27/03/2023)
' 
' Usage: New Account wizard
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.00  21/12/2017  ISS
'    2.01  27/03/2023  ISS      J030598   Not displaying if First Payment Period is not Standard
' #################################################################

' Constants
Private Superscript As String = Chr(185)

' Objects
Private mAccount As finAccount

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 PaymentCycle As String
  Dim Payments As Integer
  Dim Term As String

  ' Assume Success
  Main = True

  ' Initialise
  mAccount = DirectCast(source, finAccount)

  ' Get Event Args
  With eventArgs
    PaymentCycle = .GetString("PaymentCycle")
    Payments = .GetInteger("Payments")
    Term = .GetString("Term")
  End With

  ' Get Constants
  With ScriptInfo.Constants
  End With

  Select Case UCase(eventId)
    Case ""
      ' Main event, i.e., return main page content
      Main = CreatePage(text)

    Case "SETINSTALMENT"
      ' Update Account
      With mAccount.Calculation
        ' Clear any Overrriding Regular Payment
        .PaymentRegularOverride = 0

        ' Update Payment Cycle
        .PaymentCycleUpdate(PaymentCycle)

        Select Case .TermEntryMethod
          Case isefinAccountTermEntryMethod.NumberOfPayments
            .TermNumberOfPayments = Payments
          Case isefinAccountTermEntryMethod.Term
            .TermCycle = Term
        End Select
      End With

      ' Indicate to Close Form
      ' NOTE: For compatibility with version 1 Summary Pages, we do not use the returnValues list
      eventArgs.SetBoolean("System.CloseForm", True)
  End Select

End Function

' Create Page General
Private Function CreatePage(ByRef html As String) As Boolean

  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

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

  ' Begin Section
  sb.SectionColumnsBegin()

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

  ' Account Instalments
  sb.BlockBegin("",,,False)
  sb.SummaryTablesAppend(AccountInstalments_Summary())
  sb.BlockEnd()

  ' End Column
  sb.ColumnEnd()

  ' End Section
  sb.SectionColumnsEnd()

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Success

End Function

Private Function AccountInstalments_Summary() As ISSummaryTables

  Dim AccountCalcWorking As finAccountCalc
  Dim CurrentRow As Boolean
  Dim ErrorMessage As String
  Dim FortnightSuperscript As String
  Dim FortnightFootnote As Boolean
  Dim i As Integer  
  Dim Include As Boolean
  Dim j As Integer  
  Dim ShowFortnightlyColumn As Boolean
  Dim ShowMonthlyColumn As Boolean
  Dim ShowWeeklyColumn As Boolean
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim TermF As String
  Dim TermList As ISListReadOnly
  Dim TermM As String
  Dim TermW As String  
  Dim TermDescF As String
  Dim TermDescM As String
  Dim TermDescW As String
  Dim TermPaymentsF As Integer
  Dim TermPaymentsM As Integer
  Dim TermPaymentsW As Integer
  Dim Warnings As String

  ' Assume Success
  Success = True

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

  ' Validate
  If mAccount.Calculation.TermEntryMethod = isefinAccountTermEntryMethod.Term AndAlso mAccount.Calculation.PaymentFirstDatePeriod <> "Standard" Then
    Success = False
    ErrorMessage = "Cannot show Instalments selection for Accounts with a non-Standard First Payment Period (when entering a Term)."
  ElseIf mAccount.Calculation.Payments.Count <> 0 Then
    Success = False
    ErrorMessage = "Cannot show Instalments selection for Accounts with Overriding Payments."
  End If

  If Success Then
    ' Clone Account Calculation object (never modify the Account's version directly)
    AccountCalcWorking = mAccount.Calculation.Clone
  
    ' Find Valid Columns
    If AccountCalcWorking.AccountType.PaymentCycleLimitToList Then
      With finBL.Runtime.CreateListReadOnly(AccountCalcWorking.AccountType.PaymentCycleListResolved)
        For i = 0 To .Count - 1
          Select Case finBL.Utilities.DateCycleGetMnemonic(True, .item(i))
            Case "w" : ShowWeeklyColumn = True
            Case "f" : ShowFortnightlyColumn = True
            Case "m" : ShowMonthlyColumn = True
          End Select
        Next
      End With
    Else
      ShowWeeklyColumn = True
      ShowFortnightlyColumn = True
      ShowMonthlyColumn = True
    End If
  
    ' Find Valid Columns
    If AccountCalcWorking.TermEntryMethod = isefinAccountTermEntryMethod.Term AndAlso AccountCalcWorking.AccountType.TermLimitToList Then
      TermList = finBL.Runtime.CreateListReadOnly(AccountCalcWorking.AccountType.TermListResolved)
    End If
  End If    

  ' Create Summary Table
  With SummaryTable
    .TableClass = iseSummaryTableClass.TabularData
    .AutoStripe = True
    .WidthHtml = "auto"
  
    If Success Then
      ' Columns
      With .Columns
        .AddText("Term", 20)
        If ShowWeeklyColumn Then .AddCurrency("Weekly", 16)
        If ShowFortnightlyColumn Then .AddCurrency("Fortnightly", 16)
        If ShowMonthlyColumn Then .AddCurrency("Monthly", 16)
      End With
  
      ' Rows
      For i = 0 To 9
        ' Initialise
        Include = True

        ' Find Term
        FortnightSuperscript = ""
        Select Case i
          Case 0: TermW = "13w": TermF = "6f": TermM = "3m"
            If ShowFortnightlyColumn Then FortnightFootnote = True: FortnightSuperscript = Superscript
          Case 1: TermW = "26w": TermF = "13f": TermM = "6m"
          Case 2: TermW = "39w":TermF = "19f": TermM = "9m"
            If ShowFortnightlyColumn Then FortnightFootnote = True: FortnightSuperscript = Superscript
          Case 3: TermW = "52w": TermF = "26f": TermM = "1y"
          Case 4: TermW = "78w": TermF = "39f": TermM = "18m"
          Case 5: TermW = "104w": TermF = "52f": TermM = "2y"
          Case 6: TermW = "130w": TermF = "65f": TermM = "30m"
          Case 7: TermW = "156w": TermF = "78f": TermM = "3y"
          Case 8: TermW = "208w": TermF = "104f": TermM = "4y"
          Case 9: TermW = "260w": TermF = "130f": TermM = "5y"
        End Select
        TermPaymentsW = finBL.Runtime.NumberUtilities.ConvertToInteger(TermW)
        TermPaymentsF = finBL.Runtime.NumberUtilities.ConvertToInteger(TermF)
        If TermM.EndsWith("y") Then
          TermPaymentsM = finBL.Runtime.NumberUtilities.ConvertToInteger(TermM) * 12
        Else
          TermPaymentsM = finBL.Runtime.NumberUtilities.ConvertToInteger(TermM)
        End If
        TermDescW = finBL.Utilities.DateCycleGetDescription(False, TermW)
        TermDescF = finBL.Utilities.DateCycleGetDescription(False, TermF)
        TermDescM = finBL.Utilities.DateCycleGetDescription(False, TermM)

        ' Add Row
        If Include Then
          If AccountCalcWorking.TermEntryMethod = isefinAccountTermEntryMethod.Term AndAlso (mAccount.Calculation.TermCycleDescription = TermDescW OrElse mAccount.Calculation.TermCycleDescription = TermDescF OrElse mAccount.Calculation.TermCycleDescription = TermDescM OrElse mAccount.Calculation.TermCycleDescription = finBL.Utilities.DateCycleGetDescription(False, CStr(TermPaymentsM) & "m")) Then
            CurrentRow = True
          ElseIf AccountCalcWorking.TermEntryMethod = isefinAccountTermEntryMethod.NumberOfPayments AndAlso (mAccount.Calculation.TermCycle = TermPaymentsW & "w" OrElse mAccount.Calculation.TermCycle = TermPaymentsF & "f" OrElse mAccount.Calculation.TermCycle = TermPaymentsM & "m") Then
            CurrentRow = True
          Else
            CurrentRow = False
          End If

          With .Rows.Add.Cells
            If CurrentRow Then .Row.RowClass = iseSummaryTableRowClass.Footer

            ' Term
            .AddWiki(String.Format("{0} !!{1}!!", TermDescM, FortnightSuperscript))

            ' Weekly
            If ShowWeeklyColumn Then
              AccountCalcWorking.PaymentCycleUpdate("w")
              Select Case AccountCalcWorking.TermEntryMethod
                Case isefinAccountTermEntryMethod.NumberOfPayments: AccountCalcWorking.TermNumberOfPayments = TermPaymentsW
                Case isefinAccountTermEntryMethod.Term: AccountCalcWorking.TermCycle = TermW
              End Select

              If TermList IsNot Nothing Then
                Include = False
                With TermList
                  For j = 0 To .Count - 1
                    If finBL.Utilities.DateCycleGetMnemonic(True, .item(j)) = AccountCalcWorking.TermCycle Then
                      Include = True
                      Exit For
                    End If
                  Next j
                End With
              Else
                Include = True
              End If

              If Include Then
                If AccountCalcWorking.CalculatePayment Then
                  With .AddCurrency(AccountCalcWorking.PaymentRegular)
                    .Hyperlink = String.Format("script://event?EventId=SetInstalment&Term={0}&PaymentCycle=w&Payments={1}", TermW, TermPaymentsW)
                    If mAccount.Calculation.PaymentCycle = "w" AndAlso CurrentRow Then .CellClass = iseSummaryTableCellClass.NormalBold
                  End With
                Else
                  With .AddText("!")
                    .CellClass = iseSummaryTableCellClass.WarningBold                    
                    .Tooltip = finBL.Error.Message(True, True, True)
                  End With
                End If
              Else
                With .AddText("!")
                  .CellClass = iseSummaryTableCellClass.WarningBold                  
                  .Tooltip = "Not a valid Term"
                End With
              End If
            End If

            ' Fortnightly
            If ShowFortnightlyColumn Then
              AccountCalcWorking.PaymentCycleUpdate("f")
              Select Case AccountCalcWorking.TermEntryMethod
                Case isefinAccountTermEntryMethod.NumberOfPayments: AccountCalcWorking.TermNumberOfPayments = TermPaymentsF
                Case isefinAccountTermEntryMethod.Term: AccountCalcWorking.TermCycle = TermF
              End Select

              If TermList IsNot Nothing Then
                Include = False
                With TermList
                  For j = 0 To .Count - 1
                    If finBL.Utilities.DateCycleGetMnemonic(True, .item(j)) = AccountCalcWorking.TermCycle Then
                      Include = True
                      Exit For
                    End If
                  Next j
                End With
              Else
                Include = True
              End If

              If Include Then
                If AccountCalcWorking.CalculatePayment Then
                  With .AddCurrency(AccountCalcWorking.PaymentRegular)
                    .Hyperlink = String.Format("script://event?EventId=SetInstalment&Term={0}&PaymentCycle=f&Payments={1}", TermF, TermPaymentsF)
                    If mAccount.Calculation.PaymentCycle = "f" AndAlso CurrentRow Then .CellClass = iseSummaryTableCellClass.NormalBold
                  End With
                Else
                  With .AddText("!")
                    .CellClass = iseSummaryTableCellClass.WarningBold                    
                    .Tooltip = finBL.Error.Message(True, True, True)
                  End With
                End If
              Else
                With .AddText("!")
                  .CellClass = iseSummaryTableCellClass.WarningBold                  
                  .Tooltip = "Not a valid Term"
                End With
              End If
            End If

            ' Monthly
            If ShowMonthlyColumn Then
              AccountCalcWorking.PaymentCycleUpdate("m")
              Select Case AccountCalcWorking.TermEntryMethod
                Case isefinAccountTermEntryMethod.NumberOfPayments: AccountCalcWorking.TermNumberOfPayments = TermPaymentsM
                Case isefinAccountTermEntryMethod.Term: AccountCalcWorking.TermCycle = TermM
              End Select
  
              If TermList IsNot Nothing Then
                Include = False
                With TermList
                  For j = 0 To .Count - 1
                    If finBL.Utilities.DateCycleGetMnemonic(True, .item(j)) = AccountCalcWorking.TermCycle Then
                      Include = True
                      Exit For
                    End If
                  Next j
                End With
              Else
                Include = True
              End If
  
              If Include Then
                If AccountCalcWorking.CalculatePayment Then
                  With .AddCurrency(AccountCalcWorking.PaymentRegular)
                    .Hyperlink = String.Format("script://event?EventId=SetInstalment&Term={0}&PaymentCycle=m&Payments={1}", TermM, TermPaymentsM)
                    If mAccount.Calculation.PaymentCycle = "m" AndAlso CurrentRow Then .CellClass = iseSummaryTableCellClass.NormalBold
                  End With
                Else
                  With .AddText("!")
                    .CellClass = iseSummaryTableCellClass.WarningBold
                    .Tooltip = finBL.Error.Message(True, True, True)
                  End With
                End If
              Else
                With .AddText("!")
                  .CellClass = iseSummaryTableCellClass.WarningBold
                  .Tooltip = "Not a valid Term"
                End With
              End If
            End If
          End With
        End If
      Next
    End If
    
    ' Warnings
    Warnings = ""
    If FortnightFootnote Then Warnings &= "{{info|!!" & Superscript & "!! Fortnightly terms have been rounded down to the nearest two week period.}}"
    If Not Success Then Warnings &= "{{warning|" & ErrorMessage & "}}"
    .TextAfter = Warnings
  End With
  SummaryTables.Add("Summary", SummaryTable)

  Return SummaryTables

End Function