{{/*
  Renders a photo thumbnail. If neither a target height or target width are
  given, and the image is already in the correct orientation, no image
  processing is performed.

  Arguments
  ---------
  "Page" : A reference to the current Page
  "Height" : The target height of the image
  "Width" : The target width of the image

  Returns
  -------
  The processed thumbnail image resource
*/}}

{{- $thumbnailResource := .Page.Resources.GetMatch
                            (index .Page.Params "thumbnail" | default "[tT]humbnail*")
                        | default (index (.Page.Resources.ByType "image") 0) -}}

{{- if not $thumbnailResource -}}
  {{- errorf "No thumbnail available for %s" .Page.Permalink }}
{{- end -}}

{{ $orientation := partial "image-utilities/orientation-angle.html" $thumbnailResource }}

{{ $targetWidth := 0 }}
{{ with .Width }}
  {{ $targetWidth = . }}
{{ else }}
  {{ $targetWidth = $thumbnailResource.Width }}
{{ end }}

{{ $targetHeight := 0 }}
{{ with .Height }}
  {{ $targetHeight = . }}
{{ else }}
  {{ $targetHeight = $thumbnailResource.Height }}
{{ end }}

{{ $thumbnail := false }}
{{ if not (and (eq $orientation 0)
               (eq $targetWidth $thumbnailResource.Width)
               (eq $targetHeight $thumbnailResource.Height)) }}
  {{ $thumbnail = $thumbnailResource.Fit (printf "%dx%d r%d" $targetWidth $targetHeight (sub 360 $orientation)) }}
{{ else }}
  {{ $thumbnail = $thumbnailResource }}
{{ end }}

{{ return $thumbnail }}
