Imports System.Text.RegularExpressions
Imports WINDREAMLib

''' <summary>
''' Defines common Functions for Checking for and replacing placeholders.
''' This Class also includes a child class `Pattern` for passing around Patterns.
''' 
''' The format of all placeholders is:
''' {#TYPE#VALUE}
''' 
''' Some Examples:
''' {#INT#USERNAME}
''' {#CTRL#CMB_2}
''' {#WMI#String 39}
''' </summary>
Public Class clsPatterns
    ' Complex patterns that rely on a datasource like a Database or Windream
    Public Const PATTERN_WMI = "WMI"
    Public Const PATTERN_CTRL = "CTRL"
    ' Simple patterns that only rely on .NET functions
    Public Const PATTERN_INT = "INT"
    ' Simple patterns that rely on Data from the TBDD_USER table
    Public Const PATTERN_USER = "USER"

    Public Const USER_VALUE_PRENAME = "PRENAME"
    Public Const USER_VALUE_SURNAME = "SURNAME"
    Public Const USER_VALUE_EMAIL = "EMAIL"
    Public Const USER_VALUE_SHORTNAME = "SHORTNAME"
    Public Const USER_VALUE_USER_ID = "USER_ID"
    Public Const USER_VALUE_PROFILE_ID = "PROFILE_ID"

    Public Const INT_VALUE_USERNAME = "USERNAME"
    Public Const INT_VALUE_MACHINE = "MACHINE"
    Public Const INT_VALUE_DOMAIN = "DOMAIN"
    Public Const INT_VALUE_DATE = "DATE"

    Public Const MAX_TRY_COUNT = 100

    Private Shared regex As Regex = New Regex("{#(\w+)#([\w\s_-]+)}+")
    Private Shared allPatterns As New List(Of String) From {PATTERN_WMI, PATTERN_CTRL, PATTERN_USER, PATTERN_INT}
    Private Shared complexPatterns As New List(Of String) From {PATTERN_WMI, PATTERN_CTRL}
    Private Shared simplePatterns As New List(Of String) From {PATTERN_USER, PATTERN_INT}

    ''' <summary>
    ''' Wraps a pattern-type and -value in the common format: {#type#value}
    ''' </summary>
    Public Shared Function WrapPatternValue(type As String, value As String) As String
        Return New Pattern(type, value).ToString
    End Function


    Public Shared Function ReplaceAllValues(input As String, prename As Object, surname As Object, shortname As Object, email As Object, userId As Object, profileId As Object) As String
        Try
            Dim result = input

            result = ReplaceInternalValues(result)
            'result = ReplaceControlValues(result, Panel)
            'If Not IsNothing(document) Then result = ReplaceWindreamIndicies(result, document)
            result = ReplaceUserValues(result, prename, surname, shortname, email, userId, profileId)

            Return result
        Catch ex As Exception
            Logger.Error(ex)
            Logger.Info("Error in ReplaceAllValues:" & ex.Message)
        End Try
    End Function

    Public Shared Function ReplaceInternalValues(input As String) As String
        Try
            Dim result = input
            ' Replace Clipboard
            result = result.Replace("@Clipboard", CURRENT_CLIPBOARD_CONTENTS)
            result = result.Replace("@CLIPBOARD", CURRENT_CLIPBOARD_CONTENTS)
            result = result.Replace("@Zwischenablage", CURRENT_CLIPBOARD_CONTENTS)
            result = result.Replace("123456789", CURRENT_CLIPBOARD_CONTENTS)
            result = result.Replace("4711", CURRENT_CLIPBOARD_CONTENTS)
            ' Replace Username(s)
            While ContainsPatternAndValue(result, PATTERN_INT, INT_VALUE_USERNAME)
                result = ReplacePattern(result, PATTERN_INT, Environment.UserName)
            End While

            ' Replace Machinename(s)
            While ContainsPatternAndValue(result, PATTERN_INT, INT_VALUE_MACHINE)
                result = ReplacePattern(result, PATTERN_INT, Environment.MachineName)
            End While

            ' Replace Domainname(s)
            While ContainsPatternAndValue(result, PATTERN_INT, INT_VALUE_DOMAIN)
                result = ReplacePattern(result, PATTERN_INT, Environment.UserDomainName)
            End While

            ' Replace CurrentDate(s)
            While ContainsPatternAndValue(result, PATTERN_INT, INT_VALUE_DATE)
                result = ReplacePattern(result, PATTERN_INT, Now.ToShortDateString)
            End While

            Return result
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in ReplaceInternalValues:" & ex.Message)
        End Try
    End Function

    Public Shared Function ReplaceUserValues(input As String, prename As Object, surname As Object, shortname As Object, email As Object, userId As Object, profileId As Object) As String
        Try
            Dim result = input

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_PRENAME)
                result = ReplacePattern(input, PATTERN_USER, prename)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_USER_ID)
                result = ReplacePattern(input, PATTERN_USER, userId)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_SURNAME)
                result = ReplacePattern(input, PATTERN_USER, surname)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_SHORTNAME)
                result = ReplacePattern(input, PATTERN_USER, shortname)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_EMAIL)
                result = ReplacePattern(input, PATTERN_USER, email)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_PROFILE_ID)
                result = ReplacePattern(input, PATTERN_USER, profileId)
            End While

            Return result
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in ReplaceUserValues:" & ex.Message)
        End Try
    End Function

    Public Shared Function ReplaceControlValues(input As String, panel As Panel) As String
        Try
            Dim result = input
            Dim oTryCounter = 0

            While ContainsPattern(result, PATTERN_CTRL)
                If oTryCounter > MAX_TRY_COUNT Then
                    Throw New Exception("Max tries in ReplaceControlValues exceeded.")
                End If

                Dim controlName As String = GetNextPattern(result, PATTERN_CTRL).Value
                Dim control As Control = panel.Controls.Find(controlName, False).FirstOrDefault()

                If control IsNot Nothing Then
                    Dim value As String = control.Text
                    result = ReplacePattern(result, PATTERN_CTRL, value)
                End If

                oTryCounter += 1
            End While

            Return result
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Error in ReplaceControlValues:" & ex.Message)
        End Try
    End Function

    'Public Shared Function ReplaceWindreamIndicies(input As String, document As WMObject) As String
    '    Try
    '        Dim result = input

    '        While ContainsPattern(result, PATTERN_WMI)
    '            Dim indexName As String = GetNextPattern(result, PATTERN_WMI).Value
    '            Dim value = document.GetVariableValue(indexName)

    '            If value IsNot Nothing Then
    '                result = ReplacePattern(result, PATTERN_WMI, value)
    '            End If
    '        End While

    '        Return result
    '    Catch ex As Exception
    '        LOGGER.Error(ex)
    '        LOGGER.Info("Error in ReplaceWindreamIndicies:" & ex.Message)
    '    End Try
    'End Function

    Private Shared Function ContainsPattern(input As String, type As String) As String
        Dim elements As MatchCollection = regex.Matches(input)

        For Each element As Match In elements
            Dim t As String = element.Groups(1).Value

            If t = type Then
                Return True
            End If
        Next

        Return False
    End Function

    Public Shared Function GetNextPattern(input As String, type As String) As Pattern
        Dim elements As MatchCollection = regex.Matches(input)

        For Each element As Match In elements
            ' Pattern in input
            Dim t As String = element.Groups(1).Value
            Dim v As String = element.Groups(2).Value

            If t = type Then
                Return New Pattern(t, v)
            End If
        Next

        Return Nothing
    End Function

    Public Shared Function GetAllPatterns(input As String) As List(Of Pattern)
        Dim elements As MatchCollection = regex.Matches(input)
        Dim results As New List(Of Pattern)

        For Each element As Match In elements
            ' Pattern in input
            Dim t As String = element.Groups(1).Value
            Dim v As String = element.Groups(2).Value

            results.Add(New Pattern(t, v))
        Next

        Return results
    End Function

    Public Shared Function ReplacePattern(input As String, type As String, replacement As String) As String
        Dim elements As MatchCollection = regex.Matches(input)

        If IsNothing(replacement) Or replacement = String.Empty Then
            Return input
        End If

        For Each element As Match In elements
            ' if group 1 contains the 'pattern' the replace whole group with 'replacement'
            ' and return it
            If element.Groups(1).Value = type Then
                Return Regex.Replace(input, element.Groups(0).Value, replacement)
            End If
        Next

        ' no replacement made
        Return input
    End Function

    Private Shared Function ContainsPatternAndValue(input As String, type As String, value As String) As Boolean
        Dim elements As MatchCollection = regex.Matches(input)

        For Each element As Match In elements
            ' Pattern in input
            Dim t As String = element.Groups(1).Value
            Dim v As String = element.Groups(2).Value

            If t = type And v = value Then
                Return True
            End If
        Next

        Return False
    End Function

    Public Shared Function HasAnyPatterns(input) As Boolean
        Return allPatterns.Any(Function(p)
                                   Return HasPattern(input, p)
                               End Function)
    End Function

    Public Shared Function HasOnlySimplePatterns(input As String) As Boolean
        Return Not HasComplexPatterns(input)
    End Function

    Public Shared Function HasComplexPatterns(input As String) As Boolean
        Return complexPatterns.Any(Function(p)
                                       Return HasPattern(input, p)
                                   End Function)
    End Function

    Public Shared Function HasPattern(input As String, type As String) As Boolean
        Dim matches = regex.Matches(input)

        For Each match As Match In matches
            For Each group As Group In match.Groups
                If group.Value = type Then
                    Return True
                End If
            Next
        Next

        Return False
    End Function

    Public Class Pattern
        Public ReadOnly Property Type As String
        Public ReadOnly Property Value As String

        Public Sub New(type As String, value As String)
            Me.Type = type
            Me.Value = value
        End Sub

        Public Sub New(stringRepresentation As String)
            Dim elements As MatchCollection = regex.Matches(stringRepresentation)
            Dim first As Match = elements.Item(0)

            Dim t As String = first.Groups(1).Value
            Dim v As String = first.Groups(2).Value

            Type = t
            Value = v
        End Sub

        Public Overrides Function ToString() As String
            Return $"{{#{Type}#{Value}}}"
        End Function
    End Class
End Class