' SummaryPage2_WorkflowType_MermaidFlowchart
Option Explicit On
Option Strict On

' #################################################################
' Creates a Flowchart based upon Mermaid syntax
'
' https://mermaid.live/
' https://mermaid.js.org/intro/n00b-gettingStarted.html
' font awesome https://fontawesome.com/v5/search?o=r&m=free
' 
' Version: 1.00 (23/08/2023)
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  23/08/2023  ISS      J031523   Created
' #################################################################

' Properties
Private mMermaidCode As String
Private mWorkflowType As finWorkflowType

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

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

  ' Initialise
  mWorkflowType = DirectCast(source, finWorkflowType)

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

  ' 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 GroupIndex As Integer
  Dim i As Integer
  Dim ItemId As String
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim WorkflowTypeItem As finWorkflowTypeItem

  ' Assume Success
  Success = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Get Mermaid Code
  If Success Then
    ' Initialise
    mMermaidCode = ""
    
    ' Heading
    WriteLine("flowchart TD")

    ' Add Items
    For GroupIndex = 0 To mWorkFlowType.ItemGroups.Count - 1
      DoGroupInfo(GroupIndex, mWorkFlowType.ItemGroups(GroupIndex).Items)
    Next  

    ' Add Flow - in Reverse Order
    For GroupIndex = mWorkFlowType.ItemGroups.Count - 1 To 0 Step -1
      WorkflowTypeItem = mWorkFlowType.ItemGroups(GroupIndex)
      ItemId = String.Format("Item{0}", GroupIndex)
  
      WriteLine(String.Format("subgraph {0} [{1}]", ItemId, If(String.IsNullOrEmpty(WorkflowTypeItem.ItemId), "", WorkflowTypeItem.ItemId & ": ") & WorkflowTypeItem.Description))
      WriteLine("  direction LR")
      DoGroup(GroupIndex, WorkflowTypeItem.Items)
      WriteLine("end")
    Next
  End If

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("", isefinSummaryPageStyle.Document)
    .AppendLine("<style type='text/css'>#mySvgId {height:90%;width:90%;}</style>" )
    .HtmlHeaderEnd()
  End With

  ' Add Font Awesome
  sb.AppendLine("<link href=https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.css rel='stylesheet'>")
	
  ' Heading
  sb.AppendH1(String.Format("Mermaid flowchart for Workflow Type '{0}', {1}", mWorkFlowType.WorkFlowTypeId, mWorkFlowType.Description))
  sb.AppendLine("{{info|" & String.Format("Printed on {0}", finBL.TimeZoneFunctions.GetCurrentLocalDateTime()) & "}}")
  If Not String.IsNullOrEmpty(mWorkFlowType.Code) Then
    sb.AppendLine("{{warning|This Workflow Type has script code and this may affect the flow.|true}}")
  End If  
  sb.AppendLine(" ")

  sb.AppendLine("<div id='graphDiv'></div>")
  sb.AppendLine("<script src='https://bumbu.me/svg-pan-zoom/dist/svg-pan-zoom.js'></script>")
  sb.AppendLine("<script type='module'>")
  sb.AppendLine("   import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';")
  sb.AppendLine("   mermaid.initialize({startOnLoad:false});")
  sb.AppendLine("const drawDiagram = async function () {")
  sb.AppendLine("const element = document.querySelector('#graphDiv');")
  sb.AppendLine("const graphDefinition=`")
  sb.Append(mMermaidCode)
  sb.AppendLine("`;")
  sb.AppendLine("  const {svg} = await mermaid.render('mySvgId', graphDefinition);")
  sb.AppendLine("  element.innerHTML = svg.replace(/[ ]*max-width:[ 0-9\.]*px;/i, '');")
  sb.AppendLine("  var panZoomTiger = svgPanZoom('#mySvgId', {zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true})")
  sb.AppendLine("};")
  sb.AppendLine("await drawDiagram();")
  sb.AppendLine("</script>")

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)
  
  ' Replace temporary Mermaid tags
  html= Replace(html, "?-","{{")
  html= Replace(html, "-?","}}")
  
  ' Remove DOCTYPE
  i = InStr(html, "<!DOCTYPE html>")
  If i <> 0 Then
    html = Mid(html, i + 15)
  End If  

  Return Success

End Function

Private Sub DoGroupInfo(groupIndex As Integer, workflowTypeItems As finWorkflowTypeItems)

  Dim Icon As String
  Dim Index As Integer
  Dim ItemDescription As String
  Dim ItemDescriptionSecondary As String
  Dim ItemId As String
  Dim s As String
  Dim Shape1 As String
  Dim Shape2 As String
  Dim WorkflowTypeItem As finWorkflowTypeItem
  
  s = ""
  WriteLine(String.Format("Item{0}.groupstart([START])", groupIndex))
  For Index = 0 To workflowTypeItems.Count - 1
    WorkflowTypeItem = workflowTypeItems(Index)
    ItemId = String.Format("Item{0}.{1}", groupIndex, Index)

    ' Get Shape
    Select Case WorkflowTypeItem.ItemType
      Case isefinWorkflowItemType.AccountRestructure, isefinWorkflowItemType.PaymentArrangement, isefinWorkflowItemType.SecurityRegisterSearch
        ' Process
        Shape1 ="[[": Shape2= "]]"
      Case isefinWorkflowItemType.BankAccountEnquiry, isefinWorkflowItemType.CreditEnquiry, isefinWorkflowItemType.RegisterSecurityStatement, isefinWorkflowItemType.SecurityEnquiry
        Shape1 ="[[": Shape2= "]]"
       Case isefinWorkflowItemType.Document, isefinWorkflowItemType.Log, isefinWorkflowItemType.OutgoingCommunication, isefinWorkflowItemType.WebMail
        Shape1 ="[[": Shape2= "]]"

      Case isefinWorkflowItemType.CancelWorkflow, isefinWorkflowItemType.CloseWorkflow
        Shape1 = "[": Shape2= "<"

      Case isefinWorkflowItemType.BankAccountEnquiryReview, isefinWorkflowItemType.DecisionCard, isefinWorkflowItemType.Question, isefinWorkflowItemType.Test
        ' Decision (Diamond)
        Shape1 ="{": Shape2= "}"

      Case isefinWorkflowItemType.HtmlWidget, isefinWorkflowItemType.PageSet
        ' Input (Parallelogram)
        Shape1 ="[/": Shape2= "/]"

      Case isefinWorkflowItemType.Review, isefinWorkflowItemType.Wait
        ' Delay (Hexagon) - done as temporary  text as conflicts with templates
        'Shape1 ="{{": Shape2= "}}"
        Shape1= "?-": Shape2 = "-?"        
        
      Case Else  
        Shape1 ="[": Shape2= "]"
    End Select

    ' Get Icon
    Select Case WorkflowTypeItem.ItemType
      Case isefinWorkflowItemType.AccountRestructure
        Icon = "fa:fa-money-bill"
      Case isefinWorkflowItemType.AllocateToUser
        Icon = "fa:fa-user-edit"
      Case isefinWorkflowItemType.BankAccountEnquiry
        Icon = "fa:fa-landmark"
      Case isefinWorkflowItemType.DecisionCard
        Icon = "fa:fa-question-circle"
      Case isefinWorkflowItemType.Document
        Icon = "fa:fa-file-word"
      Case isefinWorkflowItemType.Log
        Icon = "fa:fa-sticky-note"
      Case isefinWorkflowItemType.OutgoingCommunication
        Icon = "fa:fa-phone"
      Case isefinWorkflowItemType.PaymentArrangement
        Icon = "fa:fa-heart"
      Case isefinWorkflowItemType.SecurityEnquiry
        Icon = "fa:fa-home"
      Case isefinWorkflowItemType.Wait
        Icon = "fa:fa-hourglass"
      Case Else  
        Icon = ""
    End Select
    
    ' Get Secondary Information
    ItemDescriptionSecondary = ""
    Select Case WorkflowTypeItem.ItemType
      Case isefinWorkflowItemType.BankAccountEnquiry
        If Not String.IsNullOrEmpty(WorkflowTypeItem.ServiceId) Then
          ItemDescriptionSecondary = String.Format("Service '{0}'", WorkflowTypeItem.ServiceId) 
        End If  

      Case isefinWorkflowItemType.CreditEnquiry
        If Not String.IsNullOrEmpty(WorkflowTypeItem.ServiceId) Then
          ItemDescriptionSecondary = String.Format("Service '{0}'", WorkflowTypeItem.ServiceId) 
        End If  

      Case isefinWorkflowItemType.DecisionCard
        If Not String.IsNullOrEmpty(WorkflowTypeItem.DecisionCardId) Then
          ItemDescriptionSecondary = String.Format("Decision Card '{0}'", WorkflowTypeItem.DecisionCardId) 
        End If  
        
      Case isefinWorkflowItemType.Document
        If Not String.IsNullOrEmpty(WorkflowTypeItem.DocumentId) Then
          ItemDescriptionSecondary = String.Format("Document '{0}'", WorkflowTypeItem.DocumentId) 
        End If  
        
      Case isefinWorkflowItemType.HtmlWidget
        If Not String.IsNullOrEmpty(WorkflowTypeItem.HtmlWidgetId) Then
          ItemDescriptionSecondary = String.Format("Widget '{0}'", WorkflowTypeItem.HtmlWidgetId) 
        End If  
        
      Case isefinWorkflowItemType.Log
        ItemDescriptionSecondary = String.Format("Subject '{0}'", WorkflowTypeItem.LogSubject) 

      Case isefinWorkflowItemType.PageSet
        If Not String.IsNullOrEmpty(WorkflowTypeItem.PageSetId) Then
          ItemDescriptionSecondary = String.Format("PageSet '{0}'", WorkflowTypeItem.PageSetId) 
        End If  

      Case isefinWorkflowItemType.SecurityEnquiry
        If Not String.IsNullOrEmpty(WorkflowTypeItem.ServiceId) Then
          ItemDescriptionSecondary = String.Format("Service '{0}'", WorkflowTypeItem.ServiceId) 
        End If  
    End Select

    ' Monitor Category Updates
    If finBL.Settings.MonitorCategoryAUse AndAlso WorkflowTypeItem.MonitorCategoryAUpdate AndAlso Len(WorkflowTypeItem.MonitorCategoryAId) <> 0 Then 
      If Len(ItemDescriptionSecondary) <> 0 Then ItemDescription &= "<br>" 
      ItemDescriptionSecondary &= String.format("Update {0} to '{1}'", finBL.Settings.MonitorCategoryADescriptionResolved, WorkflowTypeItem.MonitorCategoryAId)
    End If  
    If finBL.Settings.MonitorCategoryBUse AndAlso WorkflowTypeItem.MonitorCategoryBUpdate AndAlso Len(WorkflowTypeItem.MonitorCategoryBId) <> 0 Then 
      If Len(ItemDescriptionSecondary) <> 0 Then ItemDescription &= "<br>" 
      ItemDescriptionSecondary &= String.format("Update {0} to '{1}'", finBL.Settings.MonitorCategoryBDescriptionResolved, WorkflowTypeItem.MonitorCategoryBId)
    End If  
    If finBL.Settings.MonitorCategoryCUse AndAlso WorkflowTypeItem.MonitorCategoryCUpdate AndAlso Len(WorkflowTypeItem.MonitorCategoryCId) <> 0 Then 
      If Len(ItemDescriptionSecondary) <> 0 Then ItemDescription &= "<br>" 
      ItemDescriptionSecondary &= String.format("Update {0} to '{1}'", finBL.Settings.MonitorCategoryCDescriptionResolved, WorkflowTypeItem.MonitorCategoryCId)
    End If  

    ' Item Description
    ItemDescription = WordwrapText(WorkflowTypeItem.Description, 30)
    If Not String.IsNullOrEmpty(ItemDescriptionSecondary) Then
      ItemDescription &= "<br>" & ItemDescriptionSecondary
    End If  
    If Not String.IsNullOrEmpty(Icon) Then
      ItemDescription = Icon & " " & ItemDescription & "&nbsp;"
    End If  
    
    ' Output
    WriteLine(ItemId & Shape1 & PropertyValueQuote(ItemDescription, True) & Shape2)
  Next
  WriteLine(String.Format("Item{0}.groupend([END])", groupIndex))

End Sub

Private Sub DoGroup(groupIndex As Integer, workflowTypeItems As finWorkflowTypeItems)

  Dim ActionDescription As String
  Dim GroupItemId As String
  Dim i As Integer
  Dim Index As Integer
  Dim ItemId As String
  Dim ItemIdSub As String
  Dim ItemIdTo As String
  Dim ItemsFrom As ISList
  Dim OutcomeDescription As String
  Dim s As String
  Dim WorkflowTypeItem As finWorkflowTypeItem
  Dim WorkflowItemOutcomeItem As finWorkflowItemOutcomeItem
  
  ItemsFrom = finBL.Runtime.CreateList()
  
  ' Group Start Item
  GroupItemId = String.Format("Item{0}.groupstart", groupIndex)

  ' Add Group Start to force to Left
  WriteLine(GroupItemId)

  ' Add Group Start to begin
  ItemsFrom.Clear()
  ItemsFrom.Add(GroupItemId)

  ' Items
  For Index = 0 To workflowTypeItems.Count - 1
    WorkflowTypeItem = workflowTypeItems(Index)
    ItemId = String.Format("Item{0}.{1}", groupIndex, Index)
    
    For Each s In ItemsFrom
      WriteLine(String.Format("{0} --> {1}", s, ItemId))
    Next

    ItemsFrom.Clear()

    If WorkflowTypeItem.OutcomeItems.Count = 0 Then
      ItemsFrom.Add(ItemId)
    Else
      For Each WorkflowItemOutcomeItem In WorkflowTypeItem.OutcomeItems
        ItemIdSub = ItemId & PropertyValueQuote(WorkflowItemOutcomeItem.Outcome)
        
        OutcomeDescription = WorkflowItemOutcomeItem.Outcome
        If WorkflowItemOutcomeItem.Success Then OutcomeDescription = "fa:fa-check-circle " & OutcomeDescription & "&nbsp;"
        OutcomeDescription = PropertyValueQuote(OutcomeDescription, True)
        OutcomeDescription = WordwrapText(OutcomeDescription, 40)
        
        ActionDescription = WorkflowItemOutcomeItem.ActionDescription
        If String.IsNullOrEmpty(ActionDescription) Then ActionDescription = WorkflowItemOutcomeItem.Outcome
        ActionDescription = PropertyValueQuote(ActionDescription, True)
        ActionDescription = WordwrapText(ActionDescription, 30)

        ' Specials
        Select Case WorkflowItemOutcomeItem.Action
          Case isefinWorkflowItemOutcomeAction.AddItemGroup, isefinWorkflowItemOutcomeAction.AddItemGroupItems, isefinWorkflowItemOutcomeAction.SkipToItemGroup
            ' Move to Group
            WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))

            ItemIdTo = ""
            For i = 0 To mWorkFlowType.ItemGroups.Count - 1
              If StrComp(WorkflowItemOutcomeItem.ActionValue, mWorkFlowType.ItemGroups(i).ItemId, CompareMethod.Text) = 0 Then
                ItemIdTo = String.Format("Item{0}.groupstart", i)
                Exit For
              End If  
            Next   

            If Not String.IsNullOrEmpty(itemIdTo) Then
              WriteLine(String.Format("{0} .-> {1}", ItemIdSub, ItemIdTo))
            End If 
          
          Case isefinWorkflowItemOutcomeAction.CancelWorkflow, isefinWorkflowItemOutcomeAction.CloseWorkflow
            ' Stop Workflow
            WriteLine(String.Format("{0} --o |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))

          Case isefinWorkflowItemOutcomeAction.CancelWorkfowAndStartWorkflow, isefinWorkflowItemOutcomeAction.CloseWorkfowAndStartWorkflow, isefinWorkflowItemOutcomeAction.StartWorkflow
            ' Start another Workflow
             WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))

          Case isefinWorkflowItemOutcomeAction.CompleteItemGroupWithOutcome
            WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
            WriteLine(String.Format("{0} --> {1}", ItemIdSub, String.format("Item{0}.groupend", groupIndex)))

          Case isefinWorkflowItemOutcomeAction.RepeatItemGroup
            ' Reapeat the current Group
            WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
            WriteLine(String.Format("{0} --> {1}", ItemIdSub, GroupItemId))

          Case Else
            WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
            ItemsFrom.Add(ItemIdSub)
        End Select
      Next
    End If  
  Next
  
  ' Group End Item
  ItemId = String.Format("Item{0}.groupend", groupIndex)
  For Each s In ItemsFrom
    WriteLine(String.Format("{0} --> {1}", s, ItemId))
  Next
  For Each WorkflowItemOutcomeItem In mWorkFlowType.ItemGroups(groupIndex).OutcomeItems
    ItemIdSub = ItemId & "." & PropertyValueClean(WorkflowItemOutcomeItem.Outcome)
    
    OutcomeDescription = WorkflowItemOutcomeItem.Outcome
    If WorkflowItemOutcomeItem.Success Then OutcomeDescription = "fa:fa-check-circle " & OutcomeDescription & "&nbsp;"
    OutcomeDescription = PropertyValueQuote(OutcomeDescription, True)
    OutcomeDescription = WordwrapText(OutcomeDescription, 40)
    
    ActionDescription = WorkflowItemOutcomeItem.OutcomeDescription
    If Not String.IsNullOrEmpty(WorkflowItemOutcomeItem.ActionDescription) Then
      If Not String.IsNullOrEmpty(ActionDescription) Then ActionDescription &= "<br>"
      ActionDescription &= WorkflowItemOutcomeItem.ActionDescription
    End If  
    If String.IsNullOrEmpty(ActionDescription) Then ActionDescription = WorkflowItemOutcomeItem.Outcome
    ActionDescription = PropertyValueQuote(ActionDescription, True)
    ActionDescription = WordwrapText(ActionDescription, 30)

    ' Specials
    Select Case WorkflowItemOutcomeItem.Action
      Case isefinWorkflowItemOutcomeAction.AddItemGroup, isefinWorkflowItemOutcomeAction.AddItemGroupItems, isefinWorkflowItemOutcomeAction.SkipToItemGroup
        ' Move to Group
        ItemIdTo = ""
        For i = 0 To mWorkFlowType.ItemGroups.Count - 1
          If StrComp(mWorkFlowType.ItemGroups(i).ItemId, WorkflowItemOutcomeItem.ActionValue, CompareMethod.Text) = 0 Then
            ItemIdTo = String.format("Item{0}.groupstart", i)
            Exit For
          End If  
        Next   
        
        If String.IsNullOrEmpty(itemIdTo) Then
          WriteLine(String.Format("{0} .-> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
        Else  
          WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
          WriteLine(String.Format("{0} .-> {1}", ItemIdSub, ItemIdTo))
        End If 
      
      Case isefinWorkflowItemOutcomeAction.CancelWorkflow, isefinWorkflowItemOutcomeAction.CloseWorkflow
        WriteLine(String.Format("{0} --o |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
        
      Case isefinWorkflowItemOutcomeAction.RepeatItemGroup
        ' Reapeat the current Group
        WriteLine(String.Format("{0} .-> |{1}|{2}", ItemId, OutcomeDescription, GroupItemId))

      Case Else
        WriteLine(String.Format("{0} --> |{1}|{2}[{3}]", ItemId, OutcomeDescription, ItemIdSub, ActionDescription))
    End Select
  Next

End Sub

Private Function PropertyValueQuote(value As String,
                           Optional allowSpaces As Boolean = False) As String

  Dim i As Integer
  Dim QuoteValue As Boolean
  
  ' Replace Quotes
  value = Replace(value, """", "'")
  
  ' Remove Spaces?
  If Not allowSpaces Then
    value = Replace(value, " ", "")
  End If  
  
  ' Remove other invalid characters
  value = finBL.Runtime.Validation.ValidateStringAsciiPrintable(value)

  ' Quote value?
  QuoteValue = False
  For i = 1 To Len(value)
    If InStr("()[]{}", Mid(value,i,1)) <> 0 Then
      QuoteValue = True
      Exit For
    End If
  Next
  
  If QuoteValue Then
    Value = """" & value & """"
  End If
    
  Return value  

End Function

Private Function PropertyValueClean(value As String) As String

  value = Replace(value, " ", "")
  value = Replace(value, "(", "")
  value = Replace(value, ")", "")
  value = Replace(value, "[", "")
  value = Replace(value, "]", "")
  value = Replace(value, "{", "")
  value = Replace(value, "}", "")
  value = Replace(value, """", "")
  value = Replace(value, "'", "")
    
  Return value  

End Function

Private Sub WriteLine(value As String)
  
  mMermaidCode &= value & vbNewline

End Sub  

Private Function WordwrapText(value As String,
                     Optional lineLength As Integer = 30) As String
  
  Return Replace(finBL.Runtime.TextUtilities.WordWrapText(value, lineLength), vbNewline, "<br>")

End Function