param(
  [string]$PrinterName = "",
  [string]$ImageFile = ""
)

if (-not $PrinterName) {
  Write-Host "ERR_PRINTER_REQUIRED"
  exit 1
}

if (-not (Test-Path $ImageFile)) {
  Write-Host "ERR_IMAGE_NOT_FOUND"
  exit 1
}

Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms

$image = $null
$printDocument = $null

try {
  $image = [System.Drawing.Image]::FromFile($ImageFile)
  $printDocument = New-Object System.Drawing.Printing.PrintDocument
  $printDocument.PrinterSettings.PrinterName = $PrinterName
  $printDocument.DocumentName = "V2_Bridge_Graphics"
  $printDocument.PrintController = New-Object System.Drawing.Printing.StandardPrintController
  $printDocument.OriginAtMargins = $true
  $printDocument.DefaultPageSettings.Margins = New-Object System.Drawing.Printing.Margins 0, 0, 0, 0

  $handler = [System.Drawing.Printing.PrintPageEventHandler]{
    param($sender, $e)

    $graphics = $e.Graphics
    $graphics.PageUnit = [System.Drawing.GraphicsUnit]::Pixel
    $graphics.PageScale = 1
    $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::NearestNeighbor
    $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::None
    $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
    $clipBounds = $graphics.VisibleClipBounds
    $drawX = [Math]::Round($clipBounds.X)
    $drawY = [Math]::Round($clipBounds.Y)
    $drawWidth = [Math]::Round($clipBounds.Width)
    $drawHeight = [Math]::Round($clipBounds.Height)

    if ($drawWidth -le 0 -or $drawHeight -le 0) {
      $fallbackWidth = [Math]::Round(($e.PageBounds.Width / 100.0) * $graphics.DpiX)
      $fallbackHeight = [Math]::Round(($e.PageBounds.Height / 100.0) * $graphics.DpiY)
      $drawX = 0
      $drawY = 0
      $drawWidth = [Math]::Max($fallbackWidth, $image.Width)
      $drawHeight = [Math]::Max($fallbackHeight, $image.Height)
    }

    $graphics.Clear([System.Drawing.Color]::White)
    $graphics.DrawImage($image, $drawX, $drawY, $drawWidth, $drawHeight)
    $e.HasMorePages = $false
  }

  $printDocument.add_PrintPage($handler)
  $printDocument.Print()
  $printDocument.remove_PrintPage($handler)

  Write-Host "OK"
  exit 0
}
catch {
  Write-Host ("ERR_PRINT " + $_.Exception.Message)
  exit 1
}
finally {
  if ($printDocument) {
    $printDocument.Dispose()
  }
  if ($image) {
    $image.Dispose()
  }
}
