' SummaryPage2_MessagingSummary_TxtStream
Option Explicit On
Option Strict On

' #################################################################
' TxtStream SMS Messaging Report Summary Page Script
'
' Version: 1.00 (07/09/2020)
'
' Usage: SMS Messaging and Log forms
' #################################################################

' Constants

' 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 Response As ISSmsResponse_TxtStream_SendSms
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
  End With

  ' Get Service Logs
  Try
    Main = finBL.Messaging.GetServiceLogs(CInt(source), ServiceLogs)
  Catch ex As Exception
    Main = False
    finBL.Error.ErrorBeginFromException(ex)
  End Try
  If Main Then
    If ServiceLogs.Count = 0 Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log for a SMS Message.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      Select Case ServiceLogs(0).ExResponse.GetType()
        Case GetType(ISSmsResponse_TxtStream_SendSms)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISSmsResponse_TxtStream_SendSms)
        Case Else
          Main = False
          finBL.Error.ErrorBegin("Invalid Service Log." & typename(ServiceLogs(0).ExResponse) )
      End Select
    End If
  End If

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

End Function

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            response As ISSmsResponse_TxtStream_SendSms,
                            ByRef html As String) As Boolean

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  html = ""

  ' Initialise
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With HtmlSummaryPage2StringBuilder
    ' Display test watermark
    If serviceLogs(0).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("#1B3B6D", "#D0D0D0", "", "#F2F2F2")

    ' 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

  ' Body
  Me.CreatePage_TxtStream(serviceLogs, response, HtmlSummaryPage2StringBuilder)

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.AppendLine("<hr>")
  HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using " & response.ServiceName & " service.}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

Private Sub CreatePage_TxtStream(serviceLogs As ISServiceLogs,
                                 response As ISSmsResponse_TxtStream_SendSms,
                                 htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim SmsStatusUpdates As ISSmsStatusUpdates

  ' Get SMS Statuses - ignore errors
  finBL.Messaging.GetSmsStatusUpdates(serviceLogs(0), SmsStatusUpdates)

  With HtmlSummaryPage2StringBuilder
    .AppendH1(response.Request_SendSms.Message)

    .SummaryTablesAppend(Me.TxtStream_SendSms_Details(serviceLogs, response, SmsStatusUpdates))
    .SummaryTablesAppend(Me.TxtStream_SmsStatusUpdates(SmsStatusUpdates))
 End With

End Sub

Private Function TxtStream_SendSms_Details(serviceLogs As ISServiceLogs,
                                           response_SendSms As ISSmsResponse_TxtStream_SendSms,
                                           smsStatusUpdates As ISSmsStatusUpdates) As ISSummaryTables

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppLog As finAccountAppLog
  Dim AccountLog As finAccountLog
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim ExternalParty As finExternalPartyRO
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String
  Dim User As finUserRO
  Dim UserLog As finUserLog

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "SendDetails", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date Queued:", response_SendSms.Header.ResponseUtcTime, finBL.Settings.TimeZoneId)
    If response_SendSms.MessageResults.Count <> 0 Then
      .AddRowCaptionText("Message Id:", response_SendSms.MessageResults(0).MessageId)
    End If
    .AddRowCaptionText("From:", response_SendSms.Request_SendSms.ReplyEmailResolved, False)
    .AddRowCaptionText("To:", Me.FormatPhoneNumber(response_SendSms.Request_SendSms.Recipient.PhoneNumberE164))
    .AddRowCaptionText("", response_SendSms.Request_SendSms.Recipient.Name, False)

    Select Case UCase(serviceLogs(0).SourceType)
      Case "ACCOUNTLOG"
        AccountLog = finBL.CreateAccountLog()
        If AccountLog.Load(ServiceLogs(0).SourcePk) Then
          Account = finBL.CreateAccount()

          If Account.LoadPk(AccountLog.AccountPk) Then
            With .Rows.AddCaptionCodeDescription("Account:", Account.AccountId, Account.Name)
              .Cells(1).HyperlinkSetFormShow("Accounts", Account.AccountId)
            End With
            With .Rows.AddCaptionText("", "Account Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("AccountLog", CStr(AccountLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Account&parentSourceLogPk={1}", Account.AccountId, AccountLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "ACCOUNTAPPLOG"
        AccountAppLog = finBL.CreateAccountAppLog()
        If AccountAppLog.Load(ServiceLogs(0).SourcePk) Then
          AccountApp = finBL.CreateAccountApp()

          If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
            With .Rows.AddCaptionCodeDescription("Account Application:", AccountApp.AccountAppId, AccountApp.Name)
              .Cells(1).HyperlinkSetFormShow("AccountApps", AccountApp.AccountAppId)
            End With
            With .Rows.AddCaptionText("", "Account Application Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("AccountAppLog", CStr(AccountAppLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Account Application&parentSourceLogPk={1}", AccountApp.AccountAppId, AccountAppLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "CLIENTLOG"
        ClientLog = finBL.CreateClientLog()
        If ClientLog.Load(serviceLogs(0).SourcePk) Then
          ' Client
          Client = ClientLog.Client

          ' External Party?
          If Client.SpecialType = isefinClientSpecialType.ExternalParty Then
            ExternalParty = Client.ParentExternalPartyRO
          End If

          If ExternalParty Is Nothing Then
            ' Client
            With .Rows.AddCaptionCodeDescription("Client:", Client.ClientId, Client.Name)
              .Cells(1).HyperlinkSetFormShow("Clients", Client.ClientId)
            End With
            With .Rows.AddCaptionText("", "Client Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("ClientLog", CStr(ClientLog.Pk))
            End With
          Else
            ' External Party
            With .Rows.AddCaptionCodeDescription(ExternalParty.ExternalPartyTypeText & ":", ExternalParty.ExternalPartyId, ExternalParty.Name)
              .Cells(1).HyperlinkSetFormShow("ExternalParties", ExternalParty.ExternalPartyId)
            End With
            With .Rows.AddCaptionText("", ExternalParty.ExternalPartyTypeText & " Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("ClientLog", CStr(ClientLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Client&parentSourceLogPk={1}", Client.ClientId, ClientLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "USERLOG"
        UserLog = finBL.CreateUserLog()
        If UserLog.Load(serviceLogs(0).SourcePk) Then
          If finBL.Users.ExistsPk(UserLog.UserPk) Then
            User = finBL.Users.ItemByPk(UserLog.UserPk)

            With .Rows.AddCaptionCodeDescription("User:", User.UserId, User.Name)
              .Cells(1).HyperlinkSetFormShow("Users", User.UserId)
            End With
            With .Rows.AddCaptionText("", "User Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("UserLog", CStr(UserLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=User&parentSourceLogPk={1}", User.UserId, UserLog.Pk)).ShowInWebInterfaces = True
          End If
        End If
    End Select

    ' Warnings
    Warnings = ""
    If SmsStatusUpdates IsNot Nothing Then
      Select Case finBL.Messaging.Enums.iseMessaging_TxtStream_MessageStatus_FromString(smsStatusUpdates.GetCurrentStatus)
        Case iseMessaging_TxtStream_MessageStatus.Expired
          Warnings &= "{{warning|SMS Failed; Expired.}}"
        Case iseMessaging_TxtStream_MessageStatus.Received
          Warnings &= "{{info|SMS Delivered; Received by handset.}}"
        Case iseMessaging_TxtStream_MessageStatus.Unreachable
          Warnings &= "{{warning|SMS Failed; Number could not be reached.}}"
      End Select
      If smsStatusUpdates.HasReply Then
        Warnings &= "{{warning|There is a Reply to the SMS recorded.}}"
      End If
    End If
    .TextAfter = Warnings
  End With
  SummaryTables.Add("SendDetails", SummaryTable)

  Return SummaryTables

End Function

Private Function TxtStream_SmsStatusUpdates(smsStatusUpdates As ISSmsStatusUpdates) As ISSummaryTables

  Dim SmsStatusUpdate As ISSmsStatusUpdate
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If SmsStatusUpdates Is Nothing OrElse SmsStatusUpdates.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("StatusUpdates", "Status Updates", "No Status Updates found.", "StatusUpdates", 2)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Status Updates", "StatusUpdates", 2, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddDateTime("Date")
        .AddText("Status")
        .AddText("Service Log")
        .AddText("Reply")
      End With

      ' Rows
      With .Rows
        For Each SmsStatusUpdate In SmsStatusUpdates
          With .Add.Cells
            .AddDateTime2(SmsStatusUpdate.Date, True)
            .AddText(SmsStatusUpdate.StatusText)
            .AddText(CStr(SmsStatusUpdate.ServiceLogPk)).HyperlinkSetFormShow("ServiceLog", CStr(SmsStatusUpdate.ServiceLogPk))
            .AddText(SmsStatusUpdate.ReplyText)
          End With
        Next
      End With
    End With
    SummaryTables.Add("StatusUpdates", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function FormatPhoneNumber(phoneNumber As String) As String

  With finBL.Runtime.CreatePhoneNumberDetails2()
    If .ParsePhoneNumber(phoneNumber) Then
      Return .GetPhoneNumberFull(False)
    Else
      Return phoneNumber
    End If
  End With

End Function