param([switch]$FetchFromServer,[string]$PlexHost,[PSCredential]$Credential,[switch]$PassThruOnly)

$local:content = $(try{(Get-Content /run/plex.stream.counter/sessions -Raw -ErrorAction Stop)}catch{})

if( $FetchFromServer ) {
    if( ! $PlexHost ) { $PlexHost = $env:PLEX_HOST }
    if( ! $PlexHost ) { $PlexHost = 'localhost' }
    
    if( -not Credential ) { $Credential = $PlexPresetCredential }
    if( -not Credential ) {
        if( -not $env:PLEX_USERNAME -or -not $env:PLEX_PASSWORD ) {
            throw "`$env:PLEX_USERNAME AND `$env:PLEX_PASSWORD must be defined in order to read directly from server"
        }
        $Credential = New-Object   System.Management.Automation.PsCredential($env:PLEX_USERNAME,$(ConvertTo-SecureString -AsPlainText $env:PLEX_PASSWORD -Force))
    }
    $local:webResp = Invoke-WebRequest -Headers @{ "Content-Length" = "0"; "X-Plex-Client-Identifier" = "my-app" } -Credential $Credential -Method Post -Uri "https://my.plexapp.com/users/sign_in.xml"
    $local:plexHeaders = @{ "X-Plex-Token" = ([xml]$webResp.Content).user.authenticationToken }
    $webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400"
    $local:plexVersion = ([xml]$webResp.Content).MediaContainer.version
    Write-Host -ForegroundColor Cyan "Plex Version: $plexVersion"
    $webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400/status/sessions"
    $content = $webResp.Content
}

$local:PlexInfo = $(try{([xml]$content).MediaContainer}catch{})

$local:result = $PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{
    Object = $_
    Type = $_.type
    Library = $_.librarySectionTitle
    Title = $(@($_.grandparentTitle,$_.parentIndex,$_.parentTitle,$_.index,$_.title) | Where-Object {$_}) -join ' | '
    User = $_.User.title
    Offset = [TimeSpan]::FromMilliseconds($_.viewOffset).ToString() -split '\.' | select-object -first 1
    Duration = [TimeSpan]::FromMilliseconds($_.duration).ToString() -split '\.' | select-object -first 1
    Player = "$($_.Player.Platform)|$($_.Player.State)"
#   UpdateTime = [TimeSpan]::FromMilliseconds($_.).ToString()
} } 

if( $PassThruOnly ) { return $result }
$result | Format-Table