<!--
    Shortcode to render a media file as part of content where the place in text flow is not important.

    @params src Resource `src` path.
    @params link  URI or Page Resource to wrap resource in. Optional.
    @params rel Force relationship value. Optional.
-->

<!-- Variable assignment -->

{{- $src := $.Page.Resources.GetMatch ( .Get "src" ) -}}
{{- $linkedResource := $.Page.Resources.GetMatch ( .Get "link" ) -}}
{{- $valid_rel_values := partialCached "util/get_valid_rel_values.html" . -}}

<!-- Validation -->

{{- if not ( in ( slice "image" "video" ) $src.ResourceType ) -}}
    {{- errorf "Resource '%q' resource type '%q' is not valid (%q)" ( .Get "src" ) $src.ResourceType .Page.File.Path -}}
{{- end -}}

{{- if ( not $src ) -}}
  {{- errorf "No Page Resource found for src '%q' (%q)" ( .Get "src" ) .Page.File.Path -}}
{{- end -}}

{{- with .Get "rel" -}}
    {{- if not ( in $valid_rel_values . ) -}}
        {{- errorf "Invalid rel value '%q' (%q)" . .Page.File.Path -}}
    {{- end -}}
{{- end -}}

<!-- Rendering -->

<figure class="article__figure figure{{ with .Get "class" }} {{ . }}{{ end }}" role="group">
    {{- if .Get "link" -}}
        {{- if $linkedResource }}
          <a href="{{ $linkedResource.RelPermalink }}"{{ with .Get "rel" }} rel="{{ . }}"{{ end }}>
        {{ else }}
          <a href="{{ .Get "link" }}">
        {{ end }}
    {{- end -}}

    {{- if eq $src.ResourceType "image" -}}
      {{- partial "media/picture.html" $src -}}

    {{- else if eq $src.ResourceType "video" -}}
      {{- if eq $src.MediaType "video/ogg" -}}
        {{- partial "media/audio.html" $src -}}

      {{- else -}}
        {{- partial "media/video.html" ( dict "src" $src "page_file_path" .Page.File.Path ) -}}

      {{- end -}}

    {{- else if ( or ( ne $src.ResourceType "image" ) ( ne $src.ResourceType "video" ) ) -}}
        {{- errorf "No handling for resource of type %q" $src.ResourceType -}}
    {{- end -}}
    
    {{- if .Get "link" }}</a>{{ end -}}

    {{- if or ( .Get "caption" ) ( .Get "title" ) ( $src.Params.attr ) -}}
        <figcaption class="figure__caption{{ if not ( or ( .Get "caption" ) ( .Get "title" ) ) }} figure__caption--no-height{{ end }}">
            {{- if .Params.attrlink -}}<a class="figcaption__attrlink" href="{{ .Params.attrlink }}">{{- end -}}
            {{- if .Params.attr -}}<p class="figcaption__attr">{{ .Params.attr | safeHTML }}{{ with .Params.attrlicence }} <span class="figcaption__licence">{{ . | safeHTML }}</span>{{ end }}</p>{{- end -}}
            {{- if .Params.attrlink -}}</a>{{- end -}}
            {{- with .Get "title" -}}<h4 class="figcaption__title">{{ . | markdownify | safeHTML }}</h4>{{- end -}}
            {{- with .Get "caption" -}}<p class="figcaption__caption">{{ . | markdownify | safeHTML }}</p>{{- end -}}
        </figcaption>
    {{- end -}}
</figure>