# ========================================================
# Open files from WebIQ Designer workspace as workaround
# for missing write file to workspace function
# ========================================================

# --- Global variables for the main script ---
# These variables are accessible throughout the script after declaration.
[string]$sEditor                                    # Editor executable name (e.g., "notepad.exe")
[string]$sUnitClass                                 # Path to unit-classes.json relative to project root
[string]$sAppInfo                                   # Path to app-info.json relative to project root
[string]$sSrcDir                                    # Source directory name for addon
[string]$NOT_INSTALLED                              # Constant string for not installed status

[System.Collections.ArrayList]$designerFilesArray = New-Object System.Collections.ArrayList # Array to store paths of found WebIQ projects
[int]$arrayIndex           = 0                      # Counter for the number of elements in designerFilesArray
[int]$iProjects            = 0                      # Total number of found WebIQ projects
[int]$iProject             = 0                      # Loop counter for iterating through projects
[int]$iInput               = 0                      # User's selected project number (as Integer)
[string]$sInput            = ""                     # User's selected project number (as String)
[string]$sTarget           = ""                     # Full path to the selected WebIQ project folder
[string]$sFile             = ""                     # Full path to a specific file within a project (e.g., app-info.json, unit-classes.json)
[string]$sCmd              = ""                     # Command string to execute (e.g., to open editor)

# Variables used in loops or temporary assignments
[string]$objPathItem       = ""                     # Current project path in loop (renamed from objPath to avoid conflict with iProject)
[array]$arWords            = @()                    # Array of path segments
[string]$sFileWebIq        = ""                     # Full path to webiq.json for project name lookup

# --- Initialization of paths and default values ---
$sEditor = "notepad.exe"
$sUnitClass = "json\unit-classes.json"
$sAppInfo = "\.designer\app-info.json"
$sSrcDir = "addon"
$NOT_INSTALLED = "*** not installed ***"

# Get the current script path for includes
$sDirCur = $PSScriptRoot + "\"

# --- Include Tools ---
# Initializes objFSO, wshShell, StdOut, StdIn globally from tools.ps1
. (Join-Path $sDirCur "tools.ps1")

# --- Main Logic ---
getWebIQWorkspaces -sAppInfo $sAppInfo -designerFilesArray $designerFilesArray

$iProjects = $designerFilesArray.Count
Clear-Host
printLN "***************************************************" -color Green
printLN "Open WebIQ unit-classes.json file in an text editor" -color Green
printLN "***************************************************" -color Green
printLN ""

If ($iProjects -eq 0) {
  printLN "No WebIQ projects found in workspace."  -color Red
  printLN "You must load a project before you can use this tool." -color Red
  quitPrg
} Else {
  $iProject = 0 # Counter for displaying project numbers.
  ForEach ($objPathItem In $designerFilesArray) {
    $iProject = $iProject + 1 # Increment counter once per loop iteration

    $sTarget = $objPathItem + "\"
    $arWords = $sTarget.Split("\")
    $sFile = Join-Path $sTarget $sAppInfo # Path to app-info.json for project details.

    If (Test-Path $sFile -PathType Leaf) { # Verify app-info.json still exists.
      $sFileWebIq = Join-Path $sTarget "webiq.json" # Path to webiq.json for project name.
      
      print -Message ($iProject) -NoNewline
      printLN -Message (": Project/Folder:   " + (padEnd (getProjectName -sFile $sFileWebIq) 24) + "/ " + (getProjectFolder -sFile $sFile))
      printLN -Message ("   Workspace: " + $arWords[$arWords.Count - 2]) -color DarkGray
    } Else {
      printLN -Message ("WARNING: Project entry for " + $objPathItem + " seems invalid (missing " + $sAppInfo + ").") -Color Yellow
    }
  }
}

# --- User Selection with Validation Loop ---
$sInput = ""
[int]$iInput = 0 # Ensure iInput is an integer
$isValidInput = $false # Flag for the validation loop

printLN "" # Leerzeile vor der Auswahlaufforderung

# Schleife, bis eine gültige Zahl im Bereich eingegeben wird
While (-not $isValidInput) {
    print -Message ("Select project: 1-" + $iProjects + ": ") -NoNewline
    $sInput = scanf

    If ([int]::TryParse($sInput, [ref]$iInput)) {
        If ($iInput -ge 1 -and $iInput -le $iProjects) {
            $isValidInput = $true # Gültige Eingabe, Schleife beenden
        } Else {
            printLN -Message ("Invalid input. Please enter a number between 1 and " + $iProjects + ".") -Color Yellow
        }
    } Else {
        printLN -Message ("Invalid input. Please enter a valid number.") -Color Yellow
    }
}
# --- End User Selection with Validation Loop ---

# --- Process Valid Selection ---
$iProject = 0 # Reset counter to find the selected project.
ForEach ($objPathItem In $designerFilesArray) {
  $iProject = $iProject + 1
  If ($iProject -eq $iInput) {
    $sTarget = $objPathItem + "\"
    $sFile = Join-Path $sTarget $sUnitClass # Path to the specific unit-classes.json file.
    printLN "Open unit-classes.json file in editor"
    printLN $sFile
    Start-Process -FilePath $sEditor -ArgumentList $sFile -NoNewWindow
    Break # Project found and editor launched, exit loop.
  }
}

print "*** Press Enter to exit ***" -Color DarkGray
scanf