from docutils import nodes
from docutils.parsers.rst import directives, Directive


FORM1 = (
    u'<div id="{0}" class="rst-gmap" style="width:{1}; height:{2}">\r\n'
    u'</div>\r\n'
    u'<script type="text/javascript">$(function(){{\r\n'
    u'  show_gmap("{0}", {3}, {4}, {5}, "{6}");\r\n'
    u'}})</script>'
)


class Gmap(Directive):
    """ Google map directive """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {
        'height': directives.length_or_unitless,
        'width': directives.length_or_percentage_or_unitless,
        'zoom': directives.nonnegative_int,
        'latlng' : directives.unchanged,
        'title': directives.unchanged,
    }

    def run(self):
        map_id = self.arguments[0].strip()
        val = {
            'height': '240px',
            'width' : '320px',
            'zoom' : '15',
            'latlng' : '60.996572,24.462588',
            'title' : 'here!',
        }
        for options in ['height', 'width', 'zoom', 'latlng', 'title']:
            if options in self.options:
                val[options] = self.options[options]
        try:
            latitude, longitude = [x.strip() for x in val['latlng'].split(',')]
        except ValueError:
            raise self.error('Invalid latitude and/or longitude value.')
        try:
            html = FORM1.format(map_id, val['width'], val['height'],
                                latitude, longitude, val['zoom'], val['title'])
        except IOError:
            raise self.error('Could not convert to html. please contact to author.')
        return [nodes.raw('', html, format='html')]


directives.register_directive('gmap', Gmap)