[CmdletBinding(SupportsShouldProcess)]param(
    [string[]]$AddOnSlug,
    [string[]]$AddOnName,
    [switch]$InspectContainer,
    [switch]$NoPatternMatch,
    [ValidateSet('Installed','NotInstalled','Running','Stopped')]
    [string]$Status
)

$local:addons = $(Invoke-HomeAssistantCli addons)
if( -not $addons -or $addons.result -ne 'ok' ) { throw "No Addons returned" }

$addons = $addons.data.addons
switch( $Status ) {
    'Installed'    { $addons = $addons | Where-Object Installed }
    'NotInstalled' { $addons = $addons | Where-Object -Not Installed }
    'Running'      { 
            $addons = $addons | Where-Object Installed
            $InspectContainer = $true
        }
}

if( $AddOnSlug ) {
    $addons = $addons | Where-Object {
        $local:s = $_.slug;
        ($s -in $AddOnSlug) -or (
                -not $NoPatternMatch -and [bool](
                    $AddOnSlug | Where-Object { $s -match $_ }
                )
            )
    }
}
if( $InspectContainer ) {
    foreach( $local:addon in $addons ) {
        $local:c = $null
        $local:s = 'invalid'
        if( $addon.Installed ) {
            $($c = docker inspect "addon_$($addon.slug)" | ConvertFrom-Json) *>&1 | out-null
            if( $c ) { $s = $c.State.status }
        }
        $addon |
            Add-Member -MemberType NoteProperty -Name Status    -Value $s -PassThru |
            Add-Member -MemberType NoteProperty -Name Container -Value $c
    }
}

switch( $Status ) {
    'Running'      { 
        $addons = $addons | Where-Object Status -eq 'running'
    }
    'Stopped'      { 
        $addons = $addons | Where-Object Status -eq 'running'
    }
}

$addons