"""
    MoinMoin - EmbedVideo macro
    v1.0 [2018-10-29]

    This macro allows you to include a video based on its URL.
    Syntax: <<EmbedVideo("https://...."))>>

    Optional additional arguments: width and height, e.g.:
    Syntax: <<EmbedVideo("https://....", 480, 320))>>

    Links to attachments are also supported (beware: quotes are required):
    Syntax: <<EmbedVideo("attachment:foo.ogv"))>>

    @copyright: 2018 Lars Kruse <devel@sumpfralle.de>
    @license: GNU GPL3 or later
"""

from MoinMoin import wikiutil
from MoinMoin.action.AttachFile import absoluteName, getAttachUrl


def execute(macro, parameter_string):
    parameter_parser = wikiutil.ParameterParser("%(url)s%(width)s%(height)s")
    fixed_count, parsed_parameters = parameter_parser.parse_parameters(
        parameter_string)
    video_url = wikiutil.escape(parsed_parameters["url"])
    width = wikiutil.escape(parsed_parameters["width"])
    height = wikiutil.escape(parsed_parameters["height"])
    # manually parse attachment URLs
    if video_url.startswith("attachment:"):
        given_attachment_name = video_url.split(":", 1)[1]
        current_pagename = macro.formatter.page.page_name
        attach_page, real_attach_name = absoluteName(
            given_attachment_name, current_pagename)
        video_url = getAttachUrl(attach_page, real_attach_name, macro.request)
    tag_attributes = {}
    if width is not None:
        tag_attributes["width"] = width
    if height is not None:
        tag_attributes["height"] = height
    tag_attributes_text = " ".join('{}="{}"'.format(key, value)
                                   for key, value in tag_attributes.items())
    html = ('<video {} controls="controls"><source src="{}" /></video>'
            .format(tag_attributes_text, video_url))
    return macro.formatter.rawHTML(html)
