class WebAlbumTagLib {

    static namespace = "wa"

    def pictureAnchor = { attrs, body ->
        def picture = attrs.remove('picture')
        def size = attrs.remove('size')
        out << "<a href=\"${createPictureLink(picture.id, size).encodeAsHTML()}\""
        attrs.each { key, value ->
            out << " $key=\"$value\""
        }
        out << '>'
        out << body()
        out << '</a>'
    }

    def pictureImg = { attrs ->
        def picture = attrs.remove('picture')
        def size = attrs.remove('size')
        out << createPictureImage(picture, size, attrs)
    }

    def pictureLightboxAnchor = { attrs ->
        def picture = attrs.remove('picture')
        def size = attrs.remove('size')
        def lightboxSize = attrs.remove('lightboxSize')
        //def caption = picture.caption
//         if (!caption) {
            def caption = 'Show original'
//         }
        caption = caption.encodeAsHTML()
        StringBuilder sb = new StringBuilder(40)
        sb.append("<a href=\"${createPictureLink(picture.id, Image.Original).encodeAsHTML()}\"")
        attrs.each { key, value ->
            sb.append(" $key=\"$value\"")
        }
        sb.append('>')
        sb.append(caption.replaceAll(/'/, '&#39;'))
        sb.append('</a>')
        def link = sb.toString().encodeAsHTML()
        out << "<a href=\"${createPictureLink(picture.id, lightboxSize).encodeAsHTML()}\" rel=\"lightbox[list]\" title=\"${link}\">"
        out << createPictureImage(picture, size, null)
        out << '</a>'
    }

    private def createPictureImage(picture, size, attrs) {
        Integer width = 0
        Integer height = 0
        switch (size) {
            case Image.Original:
                width = picture.width
                height = picture.height
                break
            default:
                width = Image.Widths[size]
                height = Image.Widths[size]
                break
        }
//         def caption = picture.caption
//         if (!caption) {
            def caption = 'Show original'
//         }
        def alt = attrs?.remove('alt')
        if (!alt) {
            alt = caption
        }
        alt = alt.encodeAsHTML()
        def title = attrs?.remove('title')
        if (!title) {
            title = caption
        }
        title = title.encodeAsHTML()
        StringBuilder sb = new StringBuilder(40)
        sb.append("<img src=\"${createPictureLink(picture.id, size).encodeAsHTML()}\" alt=\"$alt\" title=\"$title\" width=\"$width\" height=\"$height\"")
        if (attrs) {
            attrs.each { key, value ->
                sb.append(" $key=\"$value\"")
            }
        }
        sb.append(' />')
        sb.toString()
    }

    private def createPictureLink(id, size) {
        def params = [ size: size, filename: Image.filename(id, size) ]
        createLink(url: [ controller: 'pictureDetailed', action: 'view', id: id, params: params ])
    }
}