Attribute VB_Name = "modScanToolUI"
Option Explicit

Const MOD_NAME = "ScanToolUI"

Private logFile As String

Public Enum EShellShowConstants
    essSW_HIDE = 0
    essSW_MAXIMIZE = 3
    essSW_MINIMIZE = 6
    essSW_SHOWMAXIMIZED = 3
    essSW_SHOWMINIMIZED = 2
    essSW_SHOWNORMAL = 1
    essSW_SHOWNOACTIVATE = 4
    essSW_SHOWNA = 8
    essSW_SHOWMINNOACTIVE = 7
    essSW_SHOWDEFAULT = 10
    essSW_RESTORE = 9
    essSW_SHOW = 5
End Enum

Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&
Private Const SE_ERR_ACCESSDENIED = 5        ' access denied
Private Const SE_ERR_ASSOCINCOMPLETE = 27
Private Const SE_ERR_DDEBUSY = 30
Private Const SE_ERR_DDEFAIL = 29
Private Const SE_ERR_DDETIMEOUT = 28
Private Const SE_ERR_DLLNOTFOUND = 32
Private Const SE_ERR_FNF = 2                ' file not found
Private Const SE_ERR_NOASSOC = 31
Private Const SE_ERR_PNF = 3                ' path not found
Private Const SE_ERR_OOM = 8                ' out of memory
Private Const SE_ERR_SHARE = 26

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
  (ByVal hWnd As Long, ByVal lpOperation As String, _
  ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Declare Function ShellExecuteForExplore Lib "shell32.dll" Alias "ShellExecuteA" _
  (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
  ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Public Sub Main()
    Const FUNC_NAME$ = "Main"
    On Error GoTo errorHandler
    
    Dim arg As String
    arg = Command
    ' to test batch mode
    ' args = "/optRpt=DirList /Root=c:\promis\demo\_demo  /Log=c:\temp\scantool.tdf /FileFilter=*.xml"
    
    If Len(arg) > 0 Then
        Call runCommand(arg)
    Else
        Dim frm As frmScantool
        Set frm = New frmScantool
        frm.Caption = App.Title & " " & App.Path
        frm.Show
    End If

errorHandler:
    
    If Err Then _
        MsgBox MOD_NAME & "::" & FUNC_NAME$ & " " & Err.Description
End Sub

Public Sub runCommand(args As String)
    Const FUNC_NAME$ = "runCommand"
    On Error GoTo errorHandler
    
    Dim rpt As String
    
    logFile = getArg("/log=", Command, "scantool.tab")
    
    Call writeLog("[BGN] **************************************** " & Now)
    
    Dim scanControl As clsScanControl
    Set scanControl = New clsScanControl
    
    Dim configFile As String
    configFile = getArg("/Config=", args, "")
    
    If Len(configFile) > 0 Then
        Call scanControl.loadScantoolConfig(configFile)
    Else
        scanControl.txtRootPath = getArg("/Root=", args, ".")
        scanControl.optRpt = getArg("/OptRpt=", args, "DirList")
        scanControl.txtFilFilter = getArg("/FileFilter=", args, "*")
        scanControl.txtFolderFilter = getArg("/FolderFilter=", args, "*")
        scanControl.txtSaveTo = scanControl.optRpt & ".tab"
    End If
    
    Call scanControl.setFileProcessor
    Call scanControl.runReport
    
         
errorHandler:
    
    If Err Then rpt = "ERRORS: " & MOD_NAME & "::" & FUNC_NAME$ & " " & Err.Description
       
    rpt = scanControl.Show() & rpt
    
    Call writeLog(rpt & "[END] **************************************** " & Now)
    
    Set scanControl = Nothing

End Sub

Public Sub writeLog(rpt As String)
    Const FUNC_NAME$ = "writeLog"
    On Error GoTo errorHandler

    Dim fso As Scripting.FileSystemObject
    Set fso = New Scripting.FileSystemObject
    
    Dim txt As Scripting.TextStream
    Set txt = fso.OpenTextFile(logFile, IOMode:=ForAppending, Create:=True)
    Debug.Print rpt
    Call txt.WriteLine(rpt)
    
errorHandler:

    txt.Close
    
    Set fso = Nothing
    Set txt = Nothing
    
End Sub

Private Function getArg(arg As String, cml As String, defVal As String) As String
    Const FUNC_NAME$ = "getArg"
    On Error GoTo errorHandler

    getArg = defVal
    
    Dim iStartThisToken As Integer
    iStartThisToken = InStr(1, cml, arg, vbTextCompare)
    If iStartThisToken > 0 Then
        Dim iStartNextToken
        iStartNextToken = InStr(iStartThisToken + Len(arg), cml, " /")
        If iStartNextToken = 0 Then iStartNextToken = Len(cml) + 1
        getArg = Mid$(cml, iStartThisToken + Len(arg), iStartNextToken - (iStartThisToken + Len(arg)))
        getArg = Trim(Replace(getArg, """", ""))
    End If
    Debug.Print arg & "[" & getArg & "]"
    
errorHandler:
    
    If Err Then Err.Raise 17, Description:=MOD_NAME & "::" & FUNC_NAME$ & " COMMAND LINE PARSINF ERROR: USAGE " & App.EXEName & " {/Config=file.xml /Root=x /OptRpt=x} /log=ErrLog"
End Function

Public Function ShellEx( _
ByVal sFIle As String, _
Optional ByVal eShowCmd As EShellShowConstants = essSW_SHOWDEFAULT, _
Optional ByVal sParameters As String = "", _
Optional ByVal sDefaultDir As String = "", _
Optional sOperation As String = "open", _
Optional Owner As Long = 0 _
) As Boolean

    Dim lR As Long
    Dim lErr As Long, sErr As String
    
    If (InStr(UCase$(sFIle), ".EXE") <> 0) Then
        eShowCmd = 0
    End If
    On Error Resume Next
    If (sParameters = "") And (sDefaultDir = "") Then
        lR = ShellExecuteForExplore(Owner, sOperation, sFIle, "", "", essSW_SHOWNORMAL)
    Else
        lR = ShellExecute(Owner, sOperation, sFIle, sParameters, sDefaultDir, eShowCmd)
    End If
    If (lR < 0) Or (lR > 32) Then
        ShellEx = True
    Else
        ' raise an appropriate error:
        ShellEx = False
        lErr = vbObjectError + 1048 + lR
        Select Case lR
        Case 0:                       lErr = 7: sErr = "Out of memory"
        Case ERROR_FILE_NOT_FOUND:    lErr = 53: sErr = "File not found"
        Case ERROR_PATH_NOT_FOUND:    lErr = 76: sErr = "Path not found"
        Case ERROR_BAD_FORMAT:        sErr = "The executable file is invalid or corrupt"
        Case SE_ERR_ACCESSDENIED:     lErr = 75: sErr = "Path/file access error"
        Case SE_ERR_ASSOCINCOMPLETE:  sErr = "This file type does not have a valid file association."
        Case SE_ERR_DDEBUSY:          lErr = 285: sErr = "The file could not be opened because the target application is busy. Please try again in a moment."
        Case SE_ERR_DDEFAIL:          lErr = 285: sErr = "The file could not be opened because the DDE transaction failed. Please try again in a moment."
        Case SE_ERR_DDETIMEOUT:       lErr = 286: sErr = "The file could not be opened due to time out. Please try again in a moment."
        Case SE_ERR_DLLNOTFOUND:      lErr = 48: sErr = "The specified dynamic-link library was not found."
        Case SE_ERR_NOASSOC:          sErr = "No application is associated with this file type."
        Case SE_ERR_OOM:              lErr = 7: sErr = "Out of memory"
        Case SE_ERR_SHARE:            lErr = 75: sErr = "A sharing violation occurred."
        Case Else
            sErr = "An error occurred occurred while trying to" & sOperation & " the selected file."
        End Select
                
        Err.Raise lErr, , App.EXEName & "ShellEx " & sErr
    End If

End Function

