# ========================================================
# Installs WebIQ Designer AddOn into workspace directories
#    AddOn provides important features,
#    which are currently missing in WebIQ Designer
# 2026-02-10 - bugfix correct copy for existing folder addon
# 2026-02-02 - Adapted to changed workspace folder names
# 2023-01-17 - Added folder name to install request
# 2023-01-13 - First release
# 2024-01-26 - Optimized and converted to PowerShell.
#              Uses external tools.ps1 for utility functions.
# 2024-05-16 - Added 'imglist' command option to list workspaces.
# 2024-05-16 - Integrated image listing functionality for 'imglist' command.
# 2024-05-16 - Correction: Image search starts in workspace/pics, output file in workspace/addon/json.
# 2024-05-16 - Updated: Relative paths in image list now start with '../' for HTML display.
# ========================================================
# Requires PowerShell 3.0 or later for advanced features like Foreach-Object -Parallel (not used here)
# and simplified property access.
# --- Global Variables for the Main Script ---
# These variables will be globally available after tools.ps1 is imported.
# (e.g., $global:objFSO, $global:wshShell, $global:appData, $global:NOT_INSTALLED)
#
# Flags for command line arguments.
[bool]$bAll = $false             # Flag: true for all projects, false for interactive.
[string]$sCmd = "add"            # Command: "add" for install, "del" for uninstall, "imglist" for listing workspaces. Default is "add".
[bool]$bSilent = $false          # Flag: true for silent operation (no final message).
#
# Configuration strings.
[string]$sAppInfo = "\.designer\app-info.json"  # Path to app-info.json relative to project root.
[string]$sSrcDir = "addon"                      # Source directory name for the addon.

# --- Image Listing Configuration (used when sCmd is "imglist") ---
[string]$ImgListOutputFileName = "image_list.txt" # Name of the file to write image paths to in each workspace.
[string]$ImgSearchSubDir = "pics"               # Subdirectory within the workspace where image search starts.
[string]$ImgOutputSubDir = "addon\json"         # Subdirectory within the workspace where the output file is saved.
[string]$ImgPathPrefix = "" # "..\"             # NEW: Prefix to add to each relative image path for HTML display.
$ImageExtensions = @( # Image extensions to search for in each workspace.
    "*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.tiff", "*.tif", "*.ico", "*.svg"
)
# --- End Image Listing Configuration ---

# $global:NOT_INSTALLED will be available after tools.ps1 is imported.
# Project search and selection variables.
$designerFilesArray = New-Object System.Collections.ArrayList # Clean initialization of ArrayList
[int]$iProjects = 0                    # Total number of found WebIQ projects.
# Installation/uninstallation process variables.
[string]$sToDo = "install"             # String to indicate action ("install", "delete", or "list images").
[string]$sSourceFullPath               # Full path to the source addon folder.
[string]$sVersionNew = "???"           # New version of the addon to be installed.
[int]$iCounter = 0                     # Counter for successful installations/deletions/image lists.
[string]$sAction                       # Describes the action performed (e.g., "installed", "uninstalled").
[string]$sInfo                         # Information string for final message.
# Local variables for main script logic.
[string]$sDirCur                       # Current script's directory.
[string]$sFileVersion                  # Path to the version.txt file.
[string]$sInstalled                    # Status message for installation.
[string]$sTarget                       # Full path to the WebIQ project folder.
[string]$sDir                          # Full path to the addon folder within a project.
[array]$arWords                        # Array of path segments.
[string]$sFile                         # Path to app-info.json for the current project.
[string]$sFileWebIq                    # Path to webiq.json for the current project.
[void]([int]$iProject = 0)             # Loop counter for iterating through projects.
[string]$oAnswer                       # User's answer to confirmation.
[string]$sTmp                          # Temporary path for deletion.
[System.Diagnostics.FileVersionInfo]$addonFileVersionInfo # For getting file version.

# --- Determine Script's Directory ---
# $PSScriptRoot is a built-in PowerShell variable for the script's directory.
$sDirCur = $PSScriptRoot + "\"
# --- Import Tools.ps1 ---
# This makes all functions and global variables from tools.ps1 available.
. (Join-Path $sDirCur "tools.ps1")
# --- Process Command Line Arguments ---
# $args is a built-in PowerShell variable for command line arguments.
If ($args) {
    ForEach ($arg in $args) {
        Switch ($arg.ToLower()) {
            "del"     { $sCmd = "del"; $sToDo = "delete" } # Command to delete addon
            "imglist" { $sCmd = "imglist"; $sToDo = "list images" } # Command to list images
            "all"     { $bAll = $true }
            "silent"  { $bSilent = $true }
        }
    }
}

# Only proceed with source addon folder checks if we're doing add/del operations
If ($sCmd -ne "imglist") {
    [string]$sDirRoot = $sDirCur + "..\"
    $sSourceFullPath = Join-Path $sDirRoot $sSrcDir
    # --- Check for Source Addon Folder ---
    If (-not (Test-Path $sSourceFullPath -PathType Container)) {
        printLN "ERROR: Subfolder with installation not found: $sSourceFullPath" -Color Red
        quitPrg # Exits the script cleanly.
    }
    #
    # --- Read New AddOn Version ---
    $sFileVersion = Join-Path $sSourceFullPath "json\version.txt"
    If (Test-Path $sFileVersion -PathType Leaf) {
        $sVersionNew = Get-Content $sFileVersion -First 1
    }
}

# --- Search for WebIQ Workspaces ---
# $designerFilesArray is defined as ArrayList to allow dynamic adding.
$global:sAppInfo = $sAppInfo # Make sAppInfo available globally for getWebIQWorkspaces
$global:sSrcDir = $sSrcDir   # Make sSrcDir available globally for getAddonVersion (via getWebIQWorkspaces if needed)
$global:NOT_INSTALLED = $NOT_INSTALLED
# Call the function from tools.ps1.
getWebIQWorkspaces -sAppInfo $sAppInfo -designerFilesArray $designerFilesArray
$iProjects = $designerFilesArray.Count

If ($iProjects -eq 0) {
    $sInstalled = "No WebIQ projects found in workspace.`n" + `
                  "You must load a project before you can install the AddOn."
    print $sInstalled -Color Yellow
    quitPrg
} Else {
    $iProject = 0 # Reset project counter for looping.
    Clear-Host
    printLN "Searching for WebIQ workspaces..." -Color Green

    If ($sCmd -eq "imglist") {
        printLN "Searching for image files in WebIQ Workspaces. Results will be saved to '$ImgListOutputFileName'."
    } ElseIf ($bSilent) {
        printLN "Silent $sToDo AddOn"
    } Else {
        printLN "Do you want to $sToDo the AddOn?"
    }
#
    ForEach ($objPath in $designerFilesArray) {
        $sTarget = $objPath + "\" # Full path to the WebIQ project folder (e.g., C:\...)
        $sDir = Join-Path $sTarget $sSrcDir # Full path to the target addon folder within the project.
        $arWords = $sTarget.Split("\") # Split path for display.
        $sFile = Join-Path $sTarget $sAppInfo # Path to app-info.json for the current project.
#
        If (Test-Path $sFile -PathType Leaf) {
            $iProject++
            $sFileWebIq = Join-Path $sTarget "webiq.json" # Path to webiq.json for project name.
            $sInfo = "Workspace $($iProject) of $($iProjects)" # Project counter for display.

            # Get Project Name
            $currentProjectName = getProjectName -sFile $sFileWebIq

            If ($sCmd -eq "imglist") {
                # --- START Image Listing Logic for this Workspace ---
                printLN "`nProcessing workspace: '$currentProjectName'..." -ForegroundColor Yellow
                
                # Determine the actual search path for images
                $imageSearchPath = Join-Path $sTarget $ImgSearchSubDir
                
                # List to store all found image files for this workspace
                $foundImageFiles = @()

                # Check if the image search path exists
                If (-not (Test-Path -Path $imageSearchPath -PathType Container)) {
                    printLN "  WARNING: Image search directory '$imageSearchPath' not found for this workspace. Skipping." -ForegroundColor Yellow
                } Else {
                    # Loop through each extension and search recursively within this workspace's image directory
                    foreach ($extension in $ImageExtensions) {
                        try {
                            # Search within the current workspace's image directory ($imageSearchPath)
                            $files = Get-ChildItem -Path $imageSearchPath -Recurse -Include $extension -File -ErrorAction SilentlyContinue
                            $foundImageFiles += $files
                        }
                        catch {
                            printLN "  ERROR searching for $extension in '$imageSearchPath': $($_.Exception.Message)" -ForegroundColor Red
                        }
                    }
                }

                # Variable to hold the relative paths for writing to file
                $relativePathsToSave = @()
                
                if ($foundImageFiles.Count -gt 0) {
                    $foundImageFiles | ForEach-Object {
                        # Calculate relative path from the current workspace's root ($sTarget)
                        # This means the 'pics\' part WILL BE INCLUDED.
                        $relativeName = $_.FullName.Substring($sTarget.Length)
                        # Prepend the configured HTML path prefix
                        $relativePathsToSave += $ImgPathPrefix + $relativeName
                    }   

                    # Construct the full output file path within the workspace's addon/json directory
                    $outputDir = Join-Path $sTarget $ImgOutputSubDir
                    If (-not (Test-Path -Path $outputDir -PathType Container)) {
                        try {
                            New-Item -Path $outputDir -ItemType Directory -Force | Out-Null
                            printLN "  Created output directory: '$outputDir'." -ForegroundColor DarkCyan
                        } catch {
                            printLN "  ERROR: Could not create output directory '$outputDir': $($_.Exception.Message)" -ForegroundColor Red
                            # Cannot save file if directory can't be created, skip saving for this workspace
                            continue
                        }
                    }
                    $outputFilePath = Join-Path $outputDir $ImgListOutputFileName

                    try {
                        $relativePathsToSave | Out-File -FilePath $outputFilePath -Encoding UTF8 -Force
                        printLN "  Saved $($relativePathsToSave.Count) image file names." -ForegroundColor Green
                        $iCounter++ # Count workspaces where image lists were saved
                    }
                    catch {
                        printLN "  ERROR: Writing to file '$outputFilePath' failed: $($_.Exception.Message)" -ForegroundColor Red
                    }
                } else {
                    printLN "  No image files found in '$imageSearchPath' for workspace '$currentProjectName'." -ForegroundColor DarkGray
                }
                # --- END Image Listing Logic for this Workspace ---

            } ElseIf ($bAll) { # If 'all' flag is set, skip confirmation dialog.
                $oAnswer = "y" # Simulate a 'yes' answer.
                printLN "`n*** $sInfo project: $currentProjectName ***" -Color Green
            } Else { # Otherwise, show a confirmation prompt.
                [string]$sAddOnVersion = getAddonVersion -sDir $sDir # Call the function from tools.ps1.
                printLN "`n*** Manage $sInfo ***" -Color DarkYellow
                printLN "Project:   $currentProjectName"
                printLN "Folder:    $(getProjectFolder -sFile $sFile)"
                printLN "AddOn:     $sAddOnVersion"
                printLN "Workspace: $($arWords[-2])" # -2 for the second-to-last element (folder name).
#
                If ($sAddOnVersion -eq $global:NOT_INSTALLED -and $sCmd -eq "del") { # Check $sCmd for "del"
                    $oAnswer = "n" # Skip uninstall if not installed.
                    #printLN "Note: AddOn not installed in this project. Skipping uninstall." -Color DarkGray
                } Else {
                    print   ">>> Enter y (=yes) or n (=no): " -NoNewline
                    $oAnswer = (scanf).ToLower() # Read user input using function from tools.ps1.
                }
            }
#
            If ($sCmd -ne "imglist" -and $oAnswer -eq "y") { # Only perform actions if not imglist and confirmed.
                If ($sCmd -eq "add") { # Check $sCmd for "add"
                    printLN "Installing AddOn '$sVersionNew' into '$currentProjectName'..."
                    # printLN $sSourceFullPath
                    # printLN (Join-Path $sTarget $sSrcDir)

                    Try {
                        # *** KORRIGIERTE ZEILE ***
                        # Ziel ist jetzt nur noch $sTarget, da Copy-Item den Quellordner $sSrcDir
                        # als Unterordner in $sTarget kopiert, wenn -Path ein Ordner ist.
                        Copy-Item -Path $sSourceFullPath -Destination $sTarget -Recurse -Force -ErrorAction Stop
                        $iCounter++
                        printLN "AddOn installed successfully." -Color Green
                    } Catch {
                        printLN "ERROR: Copy failed ($($_.Exception.Message))" -Color Red
                    }
                } Else { # Uninstall mode ($sCmd is "del").
                    $sTmp = Join-Path $sTarget $sSrcDir # Full path to the addon folder inside the project.
                    If (Test-Path $sTmp -PathType Container) {
                        printLN "Uninstalling AddOn from '$currentProjectName'..."
                        Try {
                            Remove-Item -Path $sTmp -Recurse -Force -ErrorAction Stop
                            $iCounter++
                            printLN "AddOn uninstalled successfully." -Color Green
                        } Catch {
                            printLN "ERROR: Deletion failed ($($_.Exception.Message))" -Color Red
                        }
                    } Else {
                        printLN "WARNING: Nothing to uninstall." -Color Yellow
                    }
                }
            }
        }
    }
    # --- Final Message ---
    If ($sCmd -eq "imglist") {
        If (-not $bSilent) {
            printLN "`nImage listing complete. Processed $iCounter WebIQ workspaces." -Color Green
        }
    } ElseIf ($bAll -or $iCounter -eq 0) { # If 'all' flag was set or no operations performed.
        If ($sCmd -eq "add") { # Check $sCmd
            $sAction = "installed"
            $sInfo = $sVersionNew # Display the new version if installed.
        } Else { # $sCmd is "del"
            $sAction = "uninstalled"
            $sInfo = "AddOn"
        }
        If (-not $bSilent) { # Only show if not in silent mode.
            printLN "`n$sInfo $sAction in $iCounter projects." -Color Green
        }
    }
}

quitPrg