Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Public Class JobConfigParser
    Private Shared JobOptionsRegex As New Regex("(?<enabled>True|False|Debug)\|(?<cron>[\w\d\s,\?*-/]*)(?:\|(?<args>(?:\w*::[^,\n]+,?)*))?")
    Private Shared JobArgumentsRegex As New Regex("(?:(?:\w+::[^,\n]+,?)?)+")
    Private Const ARGS_ITEM_DELIMITER As String = ","
    Private Const ARGS_KEYVALUE_DELIMITER As String = "::"
    Private Const ARGS_LIST_DELIMITER As String = "|"

    ''' <summary>
    ''' Parse a job config string. ex: True|0 0/3 * * * ?|Arg1::Foo,Arg2::Bar
    ''' </summary>
    ''' <param name="ConfigString"></param>
    ''' <returns>A populated JobConfig object</returns>
    Public Shared Function ParseConfig(pJobConfig As JobConfig) As JobConfig

        ' 24.11.2022: This only parses the optional Job arguments,
        ' everything is comparmentalized in the Service config
        pJobConfig.Args = ParseOptionalArguments(pJobConfig.ArgsString)
        Return pJobConfig


    End Function



    Private Shared Function ParseOptionalArguments(ArgsString As String) As Dictionary(Of String, String)
        Dim oArgsDictionary As New Dictionary(Of String, String)

        If JobArgumentsRegex.IsMatch(ArgsString) Then
            Dim oArgs As String() = ArgsString.Split(ARGS_ITEM_DELIMITER)

            For Each oArg In oArgs
                Dim oDelimiter As String() = New String() {ARGS_KEYVALUE_DELIMITER}
                Dim oArgSplit = oArg.Split(oDelimiter, StringSplitOptions.RemoveEmptyEntries)
                Regex.Split(oArg, "::")

                If oArgSplit.Length = 2 Then
                    oArgsDictionary.Add(oArgSplit(0), oArgSplit(1))
                Else
                    Throw New ArgumentException("Config Malformed")
                End If
            Next
        End If

        Return oArgsDictionary
    End Function
End Class
