"""
MoinMoin - Processor for the Gnuplot

Copyright (c) 2002 by Won-kyu Park <wkpark@kldp.org>
All rights reserved, see COPYING for details.

$Id$

Usage:
{{{#!gnuplot
plot sin(x)
}}}


changed at 2005-07-01 for MoinMoin 1.3 parser 
by Hyung-Yong Kim <yong27@biohackers.net>

"""

import string, sys, os, re, sha
from MoinMoin.action import AttachFile

config_gnuplot_terminal='png'
config_cache_dir='/home/moin/bhn'       #wikidata directory
config_vartmp_dir='/home/moin/bhn/tmp'  #temporary directory
config_external_gnuplot='/usr/bin/gnuplot'
config_gnuplot_options=''               #set blah blah
config_external_mv = "/bin/mv"

class Parser:
    """ Format gnuplot data plotting 
    """
    extensions = ['.gnuplot']

    def __init__(self, raw, request, **kw):
        """ Store the source text.
        """
        self.raw = raw
        self.request = request
        self.form = request.form
        self._ = request.getText

        # parse ex1tra arguments for excludes
        self.exclude = []

    def format(self, formatter):
        if not config_cache_dir:
            return
        lines = self.raw.split('\n')
        if lines[0].strip() == "#!gnuplot":
            del lines[0]

        text = '\n'.join(lines).strip()

        str = '\n'+text+'\n'
        str = re.sub('\n\s*![^\n]+\n','\n',str) # strip dangerous shell commands
        str = re.sub('[ ]+',' ',str) # compress all spaces
        str = re.sub('^\s*','',str) # strip out first spaces
        str = re.sub('\n\s*','\n',str)
        str = re.sub('\nset\s+(t|o|si).*\n', '\n',str)
        str = re.sub('\n+','\n',str)

        imgname = sha.new(str).hexdigest()
        imgname = imgname + "_gnuplot"

        attdir = config_cache_dir + "/gnuplot/attachments"
        outpath = "%s/%s.png" % (attdir, imgname)
        if not os.path.isdir(attdir):
            os.makedirs(attdir, 0775)

        pagename=formatter.page.page_name

        url=AttachFile.getAttachUrl(pagename,imgname+'.png',self.request)
        attach_dir=AttachFile.getAttachDir(self.request,pagename,create=1)

        term='png'
        ext='png'
        size='set size 0.5,0.6'

        if not os.path.isfile(attach_dir+'/'+imgname+'.png'):
            if not os.path.exists(outpath):
                data = open("%s/%s.plt" % (config_vartmp_dir,imgname), "w")
                data.write('set term %s\n' % term)
                data.write('%s\n' % size)
                data.write('set out "%s"\n' % outpath)
                data.write('%s\n' % config_gnuplot_options)
                data.write(str)
                data.close()
                cmd = "%(gnuplot)s < %(plot)s 2>/dev/stdout" % {
                   "gnuplot": config_external_gnuplot,
                   "plot": config_vartmp_dir + '/' + imgname + '.plt'
                }
                log=os.popen(cmd,"r")
                lines = log.read()
                log.close()
                if lines:
                    print "<pre class='errconsole'>"
                    print lines
                    print '<font color=red>If there is no fatal error, just reload this page</font>\n'
                    print "</pre>"
                    term='err'
                del lines
                os.system("rm -f " + config_vartmp_dir + "/" + imgname + ".plt")

                old_img_name=imgname+'.png'
                new_img_name=imgname+'.png'
                new_url=AttachFile.getAttachUrl(pagename,new_img_name,self.request)

                cmd='%(config_external_mv)s "%(old_img_name)s" "%(new_img_name)s" ' %{
                        "config_external_mv": config_external_mv,
                        "old_img_name":outpath,
                        "new_img_name":attach_dir+'/'+new_img_name
                }
                os.system(cmd)

                self.request.write(formatter.image(src="%s" % url, alt=str, align='absmiddle'))

        else:
                self.request.write(formatter.image(src="%s" % url, alt=str, align='absmiddle'))

