"""Python-Markdown extension: image sizing.

Syntax:
    ![alt](../assets/x.png){w=50%}        → width 50%, height auto (proportional)
    ![alt](../assets/x.png){h=50%}        → height 50%, width auto (proportional)
    ![alt](../assets/x.png){w=50%, h=300} → width 50%, max-height 300px (pixel h)
    ![alt](../assets/x.png)               → default: width 80%, height auto
"""
import re
from markdown.extensions import Extension
from markdown.inlinepatterns import ImageInlineProcessor

IMG_RE = (
    r'\!\[(?P<alt>.*?)\]\((?P<src>[^)]+)\)'
    r'(?:\{'
    r'(?:w=(?P<w>\d+%))?'
    r'(?:,\s*)?'
    r'(?:h=(?P<h>\d+)(?:%|px)?)?'
    r'\})?'
)


class SizedImageProcessor(ImageInlineProcessor):

    def handleMatch(self, m, data):
        alt = m.group('alt')
        src = m.group('src')
        w = m.group('w')
        h = m.group('h')

        src = src.replace('../assets/', 'assets/')
        src = src.replace('../circuits/output/', 'assets/')

        if w and h:
            # Both specified: h could be % or px
            style = f'width:{w}; height:{h}; max-width:none; max-height:none'
        elif w:
            # w only: auto height (proportional)
            style = f'width:{w}; height:auto; max-width:none; max-height:none'
        elif h:
            # h only: auto width (proportional)
            style = f'height:{h}; width:auto; max-width:none; max-height:none'
        else:
            # Default: 80%
            style = 'width:80%; height:auto; max-width:none; max-height:none'

        img_tag = f'<img src="{src}" alt="{alt}" style="{style}">'
        el = self.md.htmlStash.store(img_tag)
        return el, m.start(0), m.end(0)


class ImageRowProcessor(Extension):

    def extendMarkdown(self, md):
        md.inlinePatterns.register(
            SizedImageProcessor(IMG_RE, md), 'image_sized', 160,
        )
        md.inlinePatterns.deregister('image_link')


def makeExtension(**kwargs):
    return ImageRowProcessor(**kwargs)
