Imports CommandLine
Imports CommandLine.Text
Imports System.Text.RegularExpressions

Public Class ClassJumpRecord
    Private Shared ProtocolRegex As New Regex("pmo://(?<constructorId>\d+)-(?<recordId>\d+)")
    'Aufruf: PMO.exe --data pmo://10-60

    Class Options
        <[Option]("d", "data")>
        Public Property data As String
    End Class

    Public Shared Sub ParseArgs()
        Try
            Dim args() As String = Environment.GetCommandLineArgs()
            Dim options As New Options()
            Dim constructorId As Integer
            Dim recordId As Integer

            If args.Length <> 3 Then
                Exit Sub
            End If

            If (Parser.Default.ParseArguments(args, options)) Then
                Dim data As String = options.data
                Dim match = ProtocolRegex.Match(data)

                If Not match.Success Then
                    Exit Sub
                End If

                constructorId = match.Groups("constructorId").Value
                recordId = match.Groups("recordId").Value

                JumpToRecord(constructorId, recordId)
            Else
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox("Error in ParseArgs:" & vbNewLine & ex.Message)
            Exit Sub
        End Try
    End Sub

    Private Shared Sub JumpToRecord(constructorId As Integer, recordId As Integer)
        Try
            Dim constructorIdExists As Boolean = ClassDatabase.Execute_Scalar(String.Format("SELECT CONSTRUCT_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0}", constructorId))
            Dim recordIdExists As Boolean = ClassDatabase.Execute_Scalar(String.Format("SELECT GUID FROM TBPMO_RECORD WHERE GUID = {0}", recordId))

            If constructorIdExists = False Or recordIdExists = False Then
                MsgBox("Das angegebene Formular konnte nicht geöffnet werden. Grund: Die ConstructorID oder die RecordID wurde nicht gefunden." & vbNewLine & "constructorId: " & constructorId & ", recordId: " & recordId, MsgBoxStyle.Exclamation, "URL Handler")
                Exit Sub
            End If

            OpenFormConstructor(constructorId, recordId)
        Catch ex As Exception
            MsgBox("Error in JumpToRecord:" & vbNewLine & ex.Message)
            Exit Sub
        End Try
    End Sub
End Class
