"""
    MoinMoin - Processor for a LaTeX syntax
    @license: GNU GPL, see COPYING for details.

    @copyright: 2002 by Won-kyu Park <wkpark@kldp.org>
    @copyright: 2003 by Benny Siegert (added config.latex_header)
    Modified:
    2004-03-22 R.Bauer replaced config. by config_ and imported AttachFile
    2004-04-09 imported patch from Daniel Hottinger (pagestyle{empty}, -E switch of dvips,
               input of latex text replaced)
    2004-04-09 R.Bauer improvement in speed, because only if the image name is different
               a new image must be created
    2004-07-31 imported patch from Phil West (imgname = imgname + "_latex")
    2004-07-31 R.Bauer improvement to handle multipage postscript files as result of
               dvips. The number of pages is read from the resulting postscript file
	       The last extension must be png to show the resulting image files.
	       Therefore we need to move/rename the png files given from convert.
    2004-08-16 R.Bauer bug removed if only wiki text is changed
               in previous version a single page latex image was not shown again; reported first by Peter Kleiweg.
    2004-08-16 R.Bauer added break to the for loop


"""

Dependencies = []

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

config_external_latex = "/usr/bin/latex"
config_external_convert = "/usr/bin/convert"
config_external_dvips = "/usr/bin/dvips"
config_external_mv = "/bin/mv"
config_umask = 022

config_latex_cache_dir = "./data"
config_latex_cache_url = "./data"
config_latex_header = "\documentclass[a4paper,12pt]{article}\n\pagestyle{empty}"
config_latex_vartmp_dir = "./data/tmp"

def process(request, formatter, lines):
    if not config_latex_cache_dir:
    	return
    if lines[0].strip() == "#!latex":
        del lines[0]

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

    imgname = re.sub('\s+', ' ', texstr)
    imgname = sha.new(imgname).hexdigest()
    imgname = imgname + "_latex"

    attdir = config_latex_cache_dir + "/LaTex/attachments"
    atturl = config_latex_cache_url + "/LaTex/attachments"
    outpath = "%s/%s.png" % (attdir, imgname)
    outurl = "%s/%s.png" % (atturl, imgname)
    if not os.path.isdir(attdir):
        os.makedirs(attdir, 0775)

    pagename=formatter.page.page_name

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


    if not os.path.isfile(attach_dir+'/'+imgname+'.png'):
     if not os.path.exists(outpath):
        vartmp = config_latex_vartmp_dir
        data = open("%s/%s.tex" % (vartmp, imgname), "w")
        data.write('%s\n\\begin{document}\n%s\n\\end{document}' % (config_latex_header, texstr))
        data.close()

        cmd = "cd %(vartmp)s;%(latex)s %(options)s %(tex)s >/dev/null" % {
           "latex": config_external_latex,
           "vartmp": vartmp,
           "options": '-interaction=batchmode',
           "tex": imgname
        }
	os.umask(config_umask)
        os.system(cmd)
        os.system("cd %(vartmp)s; %(dvips)s -E %(imgname)s.dvi -o %(imgname)s.ps >/dev/null" % {
            "dvips": config_external_dvips,
            "vartmp": vartmp,
            "imgname": imgname,
        })

	os.system("%(convert)s -crop 0x0 -density 120x120 %(vartmp)s/%(imgname)s.ps %(outpath)s" % {
               "convert": config_external_convert,
               "vartmp": vartmp,
               "outpath": attach_dir+'/'+imgname+'.png',
               "imgname": imgname,
        })

#       How many pages ?
	id = open("%s/%s.ps" % (vartmp, imgname), "r")
	txt=id.readlines()
	id.close()

	name="%%Pages:"
        i=0
	result= -1
	for line in txt:
          if (line.count(name) == 1):
	    result=i
	    break
	  i=i+1


	n_pages=1
        if (result > -1):
	   page=txt[result]
           n_pages=int((split(page,name))[1])


        if n_pages == 1: # this is the old case
	   request.write(formatter.image(src="%s" % url, alt=texstr, align='absmiddle'))
	else: # and this is for more as one page
	  pages=range(n_pages)
	  for i in pages:
	     old_img_name=imgname+'.png.'+str(i)

	     new_img_name=imgname+'_'+str(i)+'.png'
	     new_url=AttachFile.getAttachUrl(pagename,new_img_name,request)

	     cmd="%(config_external_mv)s %(old_img_name)s %(new_img_name)s " %{

	        "config_external_mv": config_external_mv,
                "old_img_name":attach_dir+'/'+old_img_name,
		"new_img_name":attach_dir+'/'+new_img_name
	     }
             os.system(cmd)



	     request.write(formatter.image(src="%s" % new_url, alt=texstr, align='absmiddle'))


        os.system("rm -f %(vartmp)s/%(imgname)s.*" % {
            "vartmp": vartmp,
            "imgname": imgname,
        })


    else:
      request.write(formatter.image(src="%s" % url, alt=texstr, align='absmiddle'))
      ## multipage images always created



