Private/Presentation/MarketMapLayers.ps1

function Get-MarketMapLayerAvailability {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$SourceId
    )

    $displayDecision = Get-SourcePolicyDecision -Sources $Sources -SourceId $SourceId -Use display
    $redistributionDecision = Get-SourcePolicyDecision -Sources $Sources `
        -SourceId $SourceId -Use redistribution
    [pscustomobject][ordered]@{
        allowed = $displayDecision.allowed -and $redistributionDecision.allowed
        reason = if (-not $displayDecision.allowed) {
            $displayDecision.reason
        }
        elseif (-not $redistributionDecision.allowed) {
            $redistributionDecision.reason
        }
        else {
            $null
        }
        attribution = $displayDecision.attribution
    }
}

function Get-MarketMapPersistentSourceAvailability {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$SourceId
    )

    $displayDecision = Get-SourcePolicyDecision -Sources $Sources -SourceId $SourceId -Use display
    $persistenceDecision = Get-SourcePolicyDecision -Sources $Sources -SourceId $SourceId -Use persistence
    [pscustomobject][ordered]@{
        allowed = $displayDecision.allowed -and $persistenceDecision.allowed
        reason = if (-not $displayDecision.allowed) {
            $displayDecision.reason
        }
        elseif (-not $persistenceDecision.allowed) {
            $persistenceDecision.reason
        }
        else {
            $null
        }
        attribution = $displayDecision.attribution
    }
}

function Get-MarketMapAvailableCachedImagePath {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$SourceId,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Path
    )

    $availability = Get-MarketMapPersistentSourceAvailability -Sources $Sources -SourceId $SourceId
    if ($availability.allowed -and (Test-Path -LiteralPath $Path -PathType Leaf)) {
        return $Path
    }
}

function Get-MarketMapVisibleLayers {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][bool]$ExchangeLocationsRequested,
        [Parameter(Mandatory)][bool]$FinancialCentresRequested,
        [Parameter(Mandatory)][bool]$TimeZoneBoundariesRequested,
        [Parameter(Mandatory)][bool]$ExchangeLocationsAllowed,
        [Parameter(Mandatory)][bool]$FinancialCentresAllowed,
        [Parameter(Mandatory)][bool]$TimeZoneBoundariesAllowed
    )

    [pscustomobject][ordered]@{
        ExchangeLocations = $ExchangeLocationsRequested -and $ExchangeLocationsAllowed
        FinancialCentres = $FinancialCentresRequested -and $FinancialCentresAllowed
        TimeZoneBoundaries = $TimeZoneBoundariesRequested -and $TimeZoneBoundariesAllowed
    }
}

function Get-MarketMapLayerDescription {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][object]$Availability,
        [Parameter(Mandatory)][string]$Coverage,
        [Parameter(Mandatory)][string]$Timing,
        [Parameter(Mandatory)][string]$Accuracy
    )

    if (-not $Availability.allowed) {
        return "Unavailable: source rights are not approved ($($Availability.reason))."
    }
    "Source and reuse: $($Availability.attribution). Coverage: $Coverage. Updates: $Timing. Accuracy: $Accuracy."
}

function Invoke-MarketMapLayerRender {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$LayerName,
        [Parameter(Mandatory)][scriptblock]$Render,
        [Parameter(Mandatory)][System.Collections.IDictionary]$Failures
    )

    try {
        $value = & $Render
        $Failures.Remove($LayerName)
        [pscustomobject]@{ Succeeded = $true; Value = $value }
    }
    catch {
        $message = [string]$_.Exception.Message
        if (Get-Command -Name ConvertTo-SanitizedDiagnosticText -ErrorAction SilentlyContinue) {
            $message = ConvertTo-SanitizedDiagnosticText -Text $message
        }
        $Failures[$LayerName] = $message
        [pscustomobject]@{ Succeeded = $false; Value = $null }
    }
}

function Get-MarketMapLayerStatusText {
    [CmdletBinding()]
    param(
        [AllowEmptyCollection()][string[]]$UnavailableLayers = @(),
        [AllowNull()][System.Collections.IDictionary]$Failures
    )

    $parts = @(
        if ($UnavailableLayers.Count) {
            "$($UnavailableLayers.Count) map layer(s) unavailable; hover over disabled controls for details."
        }
        if ($Failures -and $Failures.Count) {
            $failedText = @($Failures.Keys | Sort-Object | ForEach-Object { "$_ ($($Failures[$_]))" }) -join '; '
            "Layer data could not be loaded: $failedText."
        }
    )
    if ($parts.Count) { $parts -join ' ' }
    else { 'Layer attribution and coverage are shown in control tooltips.' }
}

function ConvertTo-MarketMapCoordinate {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][object]$Value,
        [Parameter(Mandatory)][string]$RecordId,
        [Parameter(Mandatory)][ValidateSet('Latitude', 'Longitude')][string]$CoordinateName
    )

    $coordinate = 0.0
    if ($Value -is [bool] -or -not [double]::TryParse(
            [string]$Value,
            [System.Globalization.NumberStyles]::Float,
            [System.Globalization.CultureInfo]::InvariantCulture,
            [ref]$coordinate
        )) {
        throw "Map record '$RecordId' has an invalid $CoordinateName coordinate."
    }

    $minimum, $maximum = if ($CoordinateName -eq 'Latitude') { -90.0, 90.0 } else { -180.0, 180.0 }
    if ([double]::IsNaN($coordinate) -or [double]::IsInfinity($coordinate) -or
        $coordinate -lt $minimum -or $coordinate -gt $maximum) {
        throw "Map record '$RecordId' has an invalid $CoordinateName coordinate."
    }

    $coordinate
}

function Get-MarketMapValidatedExchangeLocations {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Exchanges
    )

    $seenIds = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::OrdinalIgnoreCase
    )
    foreach ($exchange in $Exchanges) {
        foreach ($field in @('Code', 'DisplayName', 'Latitude', 'Longitude')) {
            if ($null -eq $exchange.PSObject.Properties[$field]) {
                throw "Exchange location is missing required field '$field'."
            }
        }
        if ([string]::IsNullOrWhiteSpace([string]$exchange.Code) -or
            -not $seenIds.Add([string]$exchange.Code)) {
            throw "Exchange location ID '$($exchange.Code)' is empty or duplicated."
        }
        if ([string]::IsNullOrWhiteSpace([string]$exchange.DisplayName)) {
            throw "Exchange location '$($exchange.Code)' requires a display name."
        }
        $null = ConvertTo-MarketMapCoordinate -Value $exchange.Latitude `
            -RecordId $exchange.Code -CoordinateName Latitude
        $null = ConvertTo-MarketMapCoordinate -Value $exchange.Longitude `
            -RecordId $exchange.Code -CoordinateName Longitude
        $exchange
    }
}

function Get-MarketMapValidatedDataCenters {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$DataCenters
    )

    $seenIds = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::OrdinalIgnoreCase
    )
    foreach ($dataCenter in $DataCenters) {
        foreach ($field in @('Id', 'Name', 'Type', 'Latitude', 'Longitude')) {
            if ($null -eq $dataCenter.PSObject.Properties[$field]) {
                throw "Datacenter record is missing required field '$field'."
            }
        }
        if ([string]::IsNullOrWhiteSpace([string]$dataCenter.Id) -or
            -not $seenIds.Add([string]$dataCenter.Id)) {
            throw "Datacenter ID '$($dataCenter.Id)' is empty or duplicated."
        }
        if ([string]::IsNullOrWhiteSpace([string]$dataCenter.Name) -or
            [string]$dataCenter.Type -notin @('point', 'campus')) {
            throw "Datacenter '$($dataCenter.Id)' has an invalid name or record type."
        }

        $latitude = ConvertTo-MarketMapCoordinate -Value $dataCenter.Latitude `
            -RecordId $dataCenter.Id -CoordinateName Latitude
        $longitude = ConvertTo-MarketMapCoordinate -Value $dataCenter.Longitude `
            -RecordId $dataCenter.Id -CoordinateName Longitude
        [pscustomobject][ordered]@{
            Id = [string]$dataCenter.Id
            Name = [string]$dataCenter.Name
            Type = [string]$dataCenter.Type
            Latitude = $latitude
            Longitude = $longitude
            State = [string]$dataCenter.State
            County = [string]$dataCenter.County
            Operator = [string]$dataCenter.Operator
        }
    }
}

function Get-MarketMapValidatedFinancialCentres {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Centres,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [string[]]$ExchangeIds
    )

    $seenIds = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::OrdinalIgnoreCase
    )
    $knownExchangeIds = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::OrdinalIgnoreCase
    )
    foreach ($exchangeId in $ExchangeIds) {
        if (-not [string]::IsNullOrWhiteSpace($exchangeId)) {
            $null = $knownExchangeIds.Add($exchangeId)
        }
    }

    foreach ($centre in $Centres) {
        foreach ($field in @('Id', 'Name', 'Latitude', 'Longitude', 'ExchangeIds',
                'SourceId', 'Attribution', 'CurationStatus')) {
            if ($null -eq $centre.PSObject.Properties[$field]) {
                throw "Financial-centre record is missing required field '$field'."
            }
        }
        if ([string]::IsNullOrWhiteSpace([string]$centre.Id) -or
            -not $seenIds.Add([string]$centre.Id)) {
            throw "Financial-centre ID '$($centre.Id)' is empty or duplicated."
        }
        if ([string]::IsNullOrWhiteSpace([string]$centre.Name) -or
            [string]::IsNullOrWhiteSpace([string]$centre.SourceId) -or
            [string]::IsNullOrWhiteSpace([string]$centre.Attribution)) {
            throw "Financial centre '$($centre.Id)' requires a name, source, and attribution."
        }
        if ($centre.CurationStatus -notin @('curated', 'derived')) {
            throw "Financial centre '$($centre.Id)' must disclose curated or derived status."
        }
        $latitude = ConvertTo-MarketMapCoordinate -Value $centre.Latitude `
            -RecordId $centre.Id -CoordinateName Latitude
        $longitude = ConvertTo-MarketMapCoordinate -Value $centre.Longitude `
            -RecordId $centre.Id -CoordinateName Longitude
        $centreExchangeIds = @($centre.ExchangeIds)
        if ($centreExchangeIds.Count -eq 0) {
            throw "Financial centre '$($centre.Id)' must reference at least one exchange."
        }
        foreach ($exchangeId in $centreExchangeIds) {
            if ([string]::IsNullOrWhiteSpace([string]$exchangeId) -or
                -not $knownExchangeIds.Contains([string]$exchangeId)) {
                throw "Financial centre '$($centre.Id)' references unknown exchange '$exchangeId'."
            }
        }

        [pscustomobject][ordered]@{
            Id = [string]$centre.Id
            Name = [string]$centre.Name
            Latitude = $latitude
            Longitude = $longitude
            ExchangeIds = [string[]]$centreExchangeIds
            SourceId = [string]$centre.SourceId
            Attribution = [string]$centre.Attribution
            CurationStatus = [string]$centre.CurationStatus
        }
    }
}
function Update-MarketMapZoomCompensation {
    <#
    .SYNOPSIS
        Keeps map markers, labels, and line widths at a constant on-screen size while the
        map canvas is scaled by its zoom transform.
    #>

    param(
        [Parameter(Mandatory)][System.Windows.Controls.Panel]$Canvas,
        [Parameter(Mandatory)][double]$Zoom,
        [double]$PreviousZoom = 1.0,
        [double]$MaxMarkerSize = 40.0
    )

    if ($Zoom -le 0) { $Zoom = 1.0 }
    if ($PreviousZoom -le 0) { $PreviousZoom = 1.0 }
    $inverse = 1.0 / $Zoom

    foreach ($child in @($Canvas.Children)) {
        $isPointElement = $false
        if ($child -is [System.Windows.Controls.Button] -or $child -is [System.Windows.Controls.TextBlock]) {
            $isPointElement = $true
        }
        elseif ($child -is [System.Windows.Shapes.Ellipse]) {
            $isPointElement = $child.Width -le $MaxMarkerSize -and $child.Height -le $MaxMarkerSize
        }

        if ($isPointElement) {
            $child.RenderTransformOrigin = [System.Windows.Point]::new(0.5, 0.5)
            $child.RenderTransform = [System.Windows.Media.ScaleTransform]::new($inverse, $inverse)
            continue
        }

        # Only explicitly tagged polygons are point markers; small land or country polygons must scale with the map.
        if ($child -is [System.Windows.Shapes.Polygon] -and $child.Tag -eq 'map-point-marker' -and $child.Points.Count -gt 0) {
            $xs = @($child.Points | ForEach-Object X); $ys = @($child.Points | ForEach-Object Y)
            $minX = ($xs | Measure-Object -Minimum).Minimum; $maxX = ($xs | Measure-Object -Maximum).Maximum
            $minY = ($ys | Measure-Object -Minimum).Minimum; $maxY = ($ys | Measure-Object -Maximum).Maximum
            if (($maxX - $minX) -le $MaxMarkerSize -and ($maxY - $minY) -le $MaxMarkerSize) {
                $child.RenderTransform = [System.Windows.Media.ScaleTransform]::new(
                    $inverse, $inverse, ($minX + $maxX) / 2, ($minY + $maxY) / 2)
                continue
            }
        }

        if ($child -is [System.Windows.Shapes.Shape] -and $child.StrokeThickness -gt 0) {
            $child.StrokeThickness = $child.StrokeThickness * $PreviousZoom / $Zoom
        }
    }
}