import types


def monkeypatch_wagtail_as_syntax(image_node):
    """
    If you use wagtails 'as' syntax like this:

    {% srcset_image photo width-300 as thumbnail %}

    image_node["attrs"] are not resolved. This patch resolves
    srcset and attaches it to the returned rendition. It's a
    bit hacky but should work.
    """
    def render_patched(self, context):
        result = self._original_render(context)
        if self.output_var_name:
            rendition = context[self.output_var_name]
            rendition.srcset = self.attrs["srcset"].resolve(context)
            rendition.original = self.attrs["srcset"].original_url
        return result

    image_node._original_render = image_node.render
    image_node.render = types.MethodType(render_patched, image_node)
    return image_node