# -*- coding: UTF-8 -*-

"""
    MoinMoin - GoogleChart
    Based on text_x_mathtran.py approach of MoinMoin:ReimarBauer

    This parser creates a GoogleChart by using Google Chart Api e.g.
    url='http://chart.apis.google.com/chart?'+p
    p = urllib.urlencode(dict(chld='H', cht='qr', chs='250x250', chl=raw))

    For a detailed QR chart option list please read:
    http://code.google.com/intl/de-DE/apis/chart/docs/gallery/qr_codes.html
    Do not use the "cht" "chl" and  parameter, it specifies the chart typ!
    usage example:
    
    {{{
    #!GoogleChart
    #cht=qr
    #chld=L
    #chs=125x125
    #chl=hello world
    this is me
    }}}
    Second  Version 12.03.2011 - Small Style Changes    
    Initial Version 11.03.2011
    @copyright: 2011 by MoinMoin: Ralph Zacharias
    @license: GNU GPL, see COPYING for details.
"""
import sys
import urllib
from MoinMoin.action import cache

Dependencies = ["page"]

class Parser:
    """ GoogleChart parser """
    def __init__(self, raw, request, **kw):
        self.pagename      = request.page.page_name
        self.request       = request
        self.formatter     = request.formatter
        self.raw           = raw
        self.text =u'http://chart.apis.google.com/chart?'
        self.init_settings = False

        try:
            k, d = None, {}
            for l in self.raw.splitlines():
                if l.startswith('#'):
                    k, v = l[1:].split('=', 1)
                    d[k] = v.encode('UTF-8')
                elif k:
                    d[k] += '\n'
                    d[k] += l.encode('UTF-8')              
            self.text += urllib.urlencode(d)
            self.init_settings = True
        except ValueError, err:
            request.write(self.formatter.text('GoogleChart: Argument error'))

        if 'debug' in kw['format_args']:
            request.write(self.formatter.text(self.text))

            
    def render(self, formatter):
        """ renders formular  """
        # checks if initializing of all attributes in __init__ was done
        if not self.init_settings:
            return

        key = cache.key(self.request, itemname=self.pagename, content=self.text)

        if not cache.exists(self.request, key):
            image = urllib.urlopen(self.text)
            cache.put(self.request, key, image.read(), content_type="image/png")

        return formatter.image(src=cache.url(self.request, key), alt=self.raw)


    def format(self, formatter):
        """ parser output """
        # checks if initializing of all attributes in __init__ was done
        if self.init_settings:
            self.request.write(self.formatter.div(1, css_class="GoogleChart"))
            self.request.write(self.render(formatter))
            self.request.write(self.formatter.div(0))
 
