Private/UI/Invoke-EwWorkbenchLibraryRegistrationState.ps1

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Invoke-EwWorkbenchLibraryRegistrationState {
    [CmdletBinding()]
    param([Parameter(Mandatory)][Collections.IDictionary]$State)

    $path = [string]$State.LibraryPathBox.Text
    $hasFilters = @($State.ArtifactFilterControls.Values | ForEach-Object {
        $_.CheckBoxes | Where-Object { [bool]$_.IsChecked }
    }).Count -gt 0
    $destinationError = ''
    if (-not [string]::IsNullOrWhiteSpace($path)) {
        try {
            if (-not (Test-Path -LiteralPath (Join-Path -Path $path -ChildPath 'EvergreenLibrary.json') -PathType Leaf -ErrorAction Stop)) {
                $destinationError = 'Select an initialized library on the Library page.'
            }
        }
        catch {
            $destinationError = "Library destination is unavailable: $($_.Exception.Message)"
            Write-Verbose -Message "EvergreenUI: $destinationError"
        }
    }
    $reason = if ($null -ne $State.ActiveJobId -or $State.LibraryPromptActive) { 'Wait for the current operation to finish.' }
        elseif ([string]::IsNullOrWhiteSpace($path)) { 'Select an existing library on the Library page.' }
        elseif ($destinationError) { $destinationError }
        elseif ($null -eq $State.CurrentApp -or $State.AllArtifacts.Count -eq 0 -or $State.AppsDisplayStale) { 'Load current Artifacts for an Application first.' }
        elseif (-not $hasFilters) { 'Select at least one filter value.' }
        elseif (@($State.ArtifactsGrid.ItemsSource).Count -eq 0) { 'Select filters that match at least one Artifact.' }
        else { '' }
    $State.AddToLibraryButton.IsEnabled = [string]::IsNullOrEmpty($reason)
    $State.AddToLibraryButton.ToolTip = if ($reason) { $reason } else { "Save the selected Application and filters to $path. Download Artifacts later with Update library." }
    $State.LibraryRegistrationDestinationText.Text = if ($path) { "Library: $path" } else { 'Library: not selected' }
    $State.LibraryRegistrationDestinationText.ToolTip = if ($reason) { "$path`n$reason" } else { $path }
}