Imports System.Text.RegularExpressions
Imports DevExpress.XtraEditors
Imports DigitalData.Controls.LookupGrid
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Language.Utils

Public Class GlobixPatterns
    Private _Logger As Logger
    Private _idbdata As ClassIDBData
    Public Sub New(LogConfig As LogConfig)
        _Logger = LogConfig.GetLogger
        _idbdata = New ClassIDBData(LogConfig)
    End Sub
    ' Complex patterns that rely on a datasource like a Database or Windream
    Public Const PATTERN_WMI = "WMI"
    Public Const PATTERN_IDBA = "IDBA"
    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_LANGUAGE = "LANGUAGE"
    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 = 500

    Private myregex As Regex = New Regex("{#(\w+)#([\.\w\d\s_-]+)}+")
    Private allPatterns As New List(Of String) From {PATTERN_WMI, PATTERN_CTRL, PATTERN_IDBA, PATTERN_USER, PATTERN_INT}
    Private complexPatterns As New List(Of String) From {PATTERN_WMI, PATTERN_CTRL, PATTERN_IDBA}
    Private 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 Function WrapPatternValue(type As String, value As String) As String
        Return New Pattern(type, value).ToString
    End Function


    Public Function ReplaceAllValues(input As String, panel As Panel, prename As Object, surname As Object, shortname As Object, language As Object, email As Object, userId As Object, profileId As Object, pissql As Boolean) As String
        Try
            Dim result = input
            _Logger.Debug($"inputString BEFORE replacing: [{result}]")
            result = ReplaceInternalValues(result)
            result = ReplaceControlValues(result, panel)
            result = ReplaceIDBAttributes(My.Application.Globix.CURRENT_IDB_OBJ_ID, result, pissql)
            result = ReplaceUserValues(result, profileId)
            _Logger.Debug($"inputString AFTER replacing: [{result}]")
            Return result
        Catch ex As Exception
            _Logger.Error(ex)
            _Logger.Info("Error in ReplaceAllValues:" & ex.Message)
        End Try
    End Function

    Public Function ReplaceInternalValues(input As String) As String
        Try
            Dim result = input

            ' 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
            _Logger.Debug("sql after ReplaceInternalValues: " & input)
            Return result
        Catch ex As Exception
            _Logger.Error(ex)
            _Logger.Info("Error in ReplaceInternalValues:" & ex.Message)
        End Try
    End Function

    Public Function ReplaceUserValues(input As String, profileId As Object) As String
        Try
            Dim result = input
            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_PRENAME)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.GivenName)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_USER_ID)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.UserId)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_SURNAME)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.Surname)
            End While
            If IsDBNull(My.Application.User.ShortName) Then
                My.Application.User.ShortName = ""
            End If
            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_SHORTNAME)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.ShortName)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_LANGUAGE)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.Language)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_EMAIL)
                result = ReplacePattern(result, PATTERN_USER, My.Application.User.Email)
            End While

            While ContainsPatternAndValue(result, PATTERN_USER, USER_VALUE_PROFILE_ID)
                result = ReplacePattern(result, PATTERN_USER, profileId)
            End While
            _Logger.Debug("sql after ReplaceUserValues: " & input)
            Return result
        Catch ex As Exception
            _Logger.Error(ex)
            _Logger.Info("Error in ReplaceUserValues:" & ex.Message)
        End Try
    End Function

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

            _Logger.Debug("Input String: [{0}]", input)

            While ContainsPattern(result, PATTERN_CTRL)
                _Logger.Debug("ReplaceControlValues Try no. [{0}]", oTryCounter)

                If oTryCounter > MAX_TRY_COUNT Then
                    Throw New Exception($"Max tries in ReplaceControlValues exceeded - Result so far [{result}].")
                End If

                _Logger.Debug("Getting next pattern..")

                Dim oNextPattern = GetNextPattern(result, PATTERN_CTRL)

                If oNextPattern Is Nothing Then
                    _Logger.Debug("No Next Pattern found. Exiting!")
                    Exit While
                End If

                _Logger.Debug("Next Pattern Value: [{0}]", oNextPattern.Value)
                _Logger.Debug("Next Pattern Type: [{0}]", oNextPattern.Type)

                Dim controlName As String = oNextPattern.Value
                Dim oFoundControl As Control = Nothing
                Dim oFoundType As String = Nothing

                For Each oControl As Control In panel.Controls
                    If TypeOf oControl Is Label Then
                        Continue For
                    End If

                    _Logger.Debug("Getting control metadata from Control: [{0}]", oControl.Name)

                    If oControl.Tag Is Nothing Then
                        _Logger.Warn("No Metadata object found for control [{0}]. Skipping.", oControl.Name)
                        Continue For
                    End If

                    Dim oMeta = TryCast(oControl.Tag, GlobixControls.ControlMeta)

                    _Logger.Debug("Metadata IndexName: [{0}]", oMeta.IndexName)
                    _Logger.Debug("Metadata IndexType: [{0}]", oMeta.IndexType)
                    _Logger.Debug("Checking Control Name matches..")

                    If oMeta Is Nothing Then
                        _Logger.Warn("No Metadata found for control [{0}]. Skipping.", oControl.Name)
                        Continue For
                    End If

                    If oMeta.IndexName = controlName Then
                        _Logger.Debug("Control Name matches! Matching Control: [{0}]", controlName)

                        oFoundControl = oControl
                        oFoundType = oMeta.IndexType
                        Exit For
                    End If
                Next

                If oFoundControl IsNot Nothing Then
                    Dim oValue As String = String.Empty

                    _Logger.Debug("Found Control [{0}], continuing with setting value..", oFoundControl.Name)

                    If TypeOf oFoundControl Is TextEdit Then
                        Try
                            oValue = DirectCast(oFoundControl, TextEdit).Text
                        Catch ex As Exception
                            _Logger.Error(ex)
                            _Logger.Warn("Control Value for TextBox [{0}] could not be retrieved!", oFoundControl.Name)
                        End Try
                    ElseIf TypeOf oFoundControl Is CheckBox Then
                        Try
                            oValue = IIf(DirectCast(oFoundControl, CheckBox).Checked, 1, 0)
                        Catch ex As Exception
                            _Logger.Error(ex)
                            _Logger.Warn("Control Value for CheckBox [{0}] could not be retrieved!", oFoundControl.Name)
                        End Try
                    ElseIf TypeOf oFoundControl Is LookupControl3 Then
                        Try
                            Dim oLookupControl = DirectCast(oFoundControl, LookupControl3)

                            If oLookupControl.Properties.MultiSelect Then
                                Select Case oFoundType
                                    Case "INTEGER"
                                        oValue = String.Join(",", oLookupControl.Properties.SelectedValues)
                                    Case "VARCHAR"
                                        Dim oWrapped = oLookupControl.Properties.SelectedValues
                                        oValue = String.Join(",", oWrapped)
                                    Case Else
                                        _Logger.Warn("Lookup Control with [{0}] is not supported!", oFoundType)
                                End Select
                            Else
                                oValue = NotNull(oLookupControl.Properties.SelectedValues.Item(0), "")
                            End If
                        Catch ex As Exception
                            _Logger.Error(ex)
                            _Logger.Warn("Control Value for LookupControl2 [{0}] could not be retrieved!", oFoundControl.Name)
                        End Try
                    Else
                        _Logger.Debug("Unknown Control type for type [{0}], setting value to empty string.", oFoundControl.Name)
                        oValue = ""
                    End If

                    _Logger.Debug("Retrieved Value from Control [{0}] is: [{1}]", controlName, oValue)

                    result = ReplacePattern(result, PATTERN_CTRL, oValue)
                Else
                    _Logger.Warn("Control [{0}] not found!", controlName)
                End If

                oTryCounter += 1
            End While
            _Logger.Debug("input after ReplaceControlValues [{input}]")
            Return result
        Catch ex As Exception
            _Logger.Error(ex)
            _Logger.Info("Error in ReplaceControlValues:" & ex.Message)
            Return input
        End Try
    End Function
    Public Function ReplaceIDBAttributes(IDB_OBJ_ID As Long, pInput As String, IS_SQL As Boolean) As String
        Try
            Dim oResult = pInput
            Dim oTryCounter As Integer = 0
            While ContainsPattern(oResult, PATTERN_IDBA)

                Dim indexName As String = GetNextPattern(oResult, PATTERN_IDBA).Value
                Dim oIDBValue As Object
                If indexName = "ObjectID" Then
                    oIDBValue = IDB_OBJ_ID
                ElseIf indexName = "OBJID" Then
                    oIDBValue = IDB_OBJ_ID
                ElseIf indexName = "DocID" Then
                    oIDBValue = IDB_OBJ_ID
                Else
                    oIDBValue = _idbdata.GetVariableValue(indexName)
                End If

                If IsNothing(oIDBValue) And oTryCounter = MAX_TRY_COUNT Then
                    _Logger.Warn($"Max tries for [{indexName}] in ReplaceIDBAttributes exceeded - Replacing with [0]!")
                    Dim oReplaceValue = "{" + $"#{PATTERN_IDBA}#{indexName}" + "}"
                    oResult = oResult.Replace(oReplaceValue, 0)
                    Throw New Exception("Max tries in ReplaceIDBAttributes exceeded.")

                End If
                If oIDBValue IsNot Nothing Or Not IsDBNull(oIDBValue) Then
                    Dim oReplaceValue = "{" + $"#{PATTERN_IDBA}#{indexName}" + "}"
                    If IS_SQL = True Then
                        _Logger.Debug($"IS_SQL = True - oReplaceValue = [{oReplaceValue}]")
                        If indexName <> "ObjectID" And indexName <> "OBJID" And indexName <> "DocID" Then
                            Try
                                oIDBValue = oIDBValue.Replace("'", "''")
                            Catch ex As Exception
                                _Logger.Warn($"Invalid IDBValue for [{indexName}] in ReplaceIDBAttributes [{ex.Message}] - Replacing with [0]!")
                                oIDBValue = 0
                            End Try

                        End If
                        _Logger.Debug($"oIDBValue = {oIDBValue}")
                    End If
                    oResult = oResult.Replace(oReplaceValue, oIDBValue)
                Else
                    _Logger.Warn($"IDBValue for [{indexName}] in ReplaceIDBAttributes is nothing or dbnull - Replacing with [0]!")
                    Dim oReplaceValue = "{" + $"#{PATTERN_IDBA}#{indexName}" + "}"
                    oResult = oResult.Replace(oReplaceValue, 0)
                End If
                oTryCounter += 100
            End While
            _Logger.Debug("sql after ReplaceIDBAttributes: " & pInput)
            Return oResult
        Catch ex As Exception
            _Logger.Error(ex)
            _Logger.Info("Error in ReplaceIDBAttributes:" & ex.Message)
            Return pInput
        End Try
    End Function

    Private Function ContainsPattern(input As String, type As String) As Boolean
        Dim elements As MatchCollection = myregex.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 Function GetNextPattern(input As String, type As String) As Pattern
        Dim elements As MatchCollection = myregex.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 Function GetAllPatterns(input As String) As List(Of Pattern)
        Dim elements As MatchCollection = myregex.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 Function ReplacePattern(input As String, type As String, replacement As String) As String
        Dim elements As MatchCollection = myregex.Matches(input)

        If IsNothing(replacement) 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 Function ContainsPatternAndValue(input As String, type As String, value As String) As Boolean
        Dim elements As MatchCollection = myregex.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 Function HasAnyPatterns(pInput As String) As Boolean
        Return allPatterns.Any(Function(p)
                                   Return HasPattern(pInput, p)
                               End Function)
    End Function

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

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

    Public Function HasPattern(input As String, type As String) As Boolean
        Dim matches = myregex.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 = myregex.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
