"""restructuredtext django utilities and extensions

"""
YOUTUBE_EMDED = """
<object width="%(width)d" height="%(height)d">
<param name="movie" value="http://www.youtube.com/v/%(id)s&hl=en&fs=1"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/%(id)s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="%(width)d" height="%(height)d"></embed>
</object>
"""

from docutils import nodes
from docutils.parsers.rst import directives
from docutils.parsers.rst import Directive

def align(argument):
    """Conversion function for the "align" option."""
    return directives.choice(argument, ('left', 'right', 'top', 'bottom'))

class YouTube(Directive):

    required_arguments = 1
    optional_arguments = 3
    final_argument_whitespace = True
    option_spec = {'height': directives.nonnegative_int,
                   'width': directives.nonnegative_int,
                   'align': align,}
    has_content = False

    def run(self):
        id = self.arguments[0].strip()
        if not id.isalnum():
            error = self.reporter.error(
                'Error in "%s" directive: invalid youtube video id: %s' % (self.name, id),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error]

        self.options['id'] = id
        self.options.setdefault('width', 425)
        self.options.setdefault('height', 344)
        if 'align' in self.options:
            self.options['align'] = " align=\"%s\" " % self.options['align']
        return [nodes.raw('', YOUTUBE_EMDED % self.options, format='html')]

directives.register_directive('youtube', YouTube)

from templatetags.restructuredtext import restructuredparts, restructuredtext, restructuredtext_has_errors

## RED_FLAG: Very odd hack workaround for a RST processing problem
## hack processing to fix issue with django admin of all things!
## not sure why this fixes things either
## for some reason adding this line and processing some bad RST before the admin
## can register its ROLE handlers (django.contrb.admin.utils) causes them
## not to be called on the text below. If the admin.utils module is imported
## before docutils ever sees an error like this, then that code IS called
## but does not have the context properly set? all very odd. --DougN
restructuredtext('`Available as 1.0 since September, 2007 <http://www.modwsgi.org/>`')
