"""
    MoinMoin - Parser for GANTT data based on pygantt from http://www.logilab.org/projects/pygantt

    Copyright (c) 2003 by Reimar Bauer <R.Bauer@fz-juelich.de>

    This routine is published under the GNU Library General Public License


    PURPOSE:
        This parser is used to visualize gantt data in MoinMoin.

    CALLING SEQUENCE:
       {{{
       #!Gantt [name=name, renderer=renderer, width=width, height=height,
                usdates=, datesinbars=, rappel=,display-resources=,
        timestep=timestep,detail=[0,1,2,3],datesinbars=,
        view-begin=view-begin,view-end=view-end ]
       }}}


    KEYWORD PARAMETERS:

       parts of the descriptions are taken from the man page of pygantt

       name=name: optional if set this is the name of the gantt result image
       renderer=renderer: default is png, optional if set the type
                [tiff, jpeg, png,gif or svg] is used to tender the  gantt chart
       width=width: optional if set it is the width of the output image
       height=height: optional if set it is the height of the outputt image

       usdates=: optional US can't help write dates backwards...
       datesinbars=: optional write begin/end dates in task bars.
       rappel=: optional recall tasks'title on the left hand side of the diagram
       display-resources=:: optional Display resources on the Gantt chart
       timestep=timestep: optional timeline increment in days for diagram [default=1].
       detail=detail: optional detail level [0=no 1=duration/status 2=begin/end 3=all].
       datesinbars=: optional write begin/end dates in task bars.
       view-begin=view-begin: optional view begin date, as in --view-begin=2000/12/24.
       view-end=view-end: optional view end date, as in --view-end=2000/12/24.

    EXAMPLE:
{{{
{ { {#!Gantt view-end=2005/03/14,
<project xmlns:pg="http://www.logilab.org/namespaces/pygantt_docbook" id="monprojet">
  <label>Specification</label>
  <task id="module">
    <label>Module Gantt.py</label>
    <task id="func1">
      <label>Implementation Parser</label>
      <duration>2</duration>
      <constraint type="begin-after-date">2005/03/03</constraint>
    </task>
    <task id="func2">
      <label>Testing</label>
      <duration>3</duration>
      <constraint type="begin-after-date">2005/03/05</constraint>
    </task>
  </task>
  <task id="documentation">
    <label>Documentation</label>
    <task id="doc_func1">
      <label>Documentation Gantt.py</label>
      <duration>1</duration>
      <constraint type="begin-after-end">func1</constraint>
    </task>
    <task id="doc_func2">
      <label>Examples</label>
      <duration>3</duration>
      <constraint type="begin-after-end">func2</constraint>
    </task>
  </task>
</project>
} } }
}}}

    PROCEDURE:
      This parser uses the pygantt from http://www.logilab.org/projects/pygantt

      Please remove the version number from the file.

    RESTRICTIONS:

    MODIFICATION:
        Copyright (c) 2003 by Reimar Bauer <R.Bauer@fz-juelich.de>

        This routine is published under the GNU Library General Public License

        2004-04-15 : Daniel Hottinger code fix to work with moin 1.2.1

        2005-03-05: changed to parser Vesion: 1.3.3-1
        2005-04-12: 1.3.3-2 bug fixed the parser does not work on subpages recogniced by JunHu
                  :         bug fixed if highligting by e.g. search was used.


    DISCUSSION:

"""
Dependencies = []
import string, os, re, sha


from MoinMoin.Page import Page
from MoinMoin import wikiutil,config
from MoinMoin.action import AttachFile

def param_test(listof,key):
    for arg in listof:
        if (arg == key):
           return(1)
    return(0)

class Parser:
    def __init__(self, raw, request, **kw):

        self.raw = raw
        self.request = request
        self.kw = []
        for arg in kw.get('format_args','').split(','):
           self.kw.append(arg)

    def format(self, formatter):

        lines = self.raw.split('\n')

        args=self.kw

        kw ={} # create a dictionary for the formatter.image call
        exclude = []

        texstr = ''.join(args)+'\n'.join(lines).strip()
        imgname = re.sub('\s+', ' ', texstr)
        imgname = sha.new(imgname).hexdigest()
        kw['name'] = imgname + "_gantt"

        pgparams=['usdates','datesinbars','rappel','display-resources','timestep','detail',
                  'datesinbars','view-begin','view-end' ]

        kw['renderer'] = 'png'
        txt=''

        count=0


        for a in args :
              if (a.find('=') > -1):
                  count=count+1
                  key=a.split('=')
                  sep='='
                  if (key[1].strip() == '') :
                      sep=''
                  if (param_test(pgparams,str(key[0].strip())) == 1):
                      txt +=" --%(arg)s%(sep)s%(val)s" %{
                          "arg":key[0].strip(),
                          "sep":sep,
                          "val":key[1].strip()}

                  else:
                      kw[str(key[0].strip())]=wikiutil.escape(string.join(key[1],'').strip(), quote=1)

        pagename=formatter.page.page_name


        file_name="%(name)s.%(renderer)s" %{
              "name":kw['name'],
              "renderer":kw['renderer']}

        attach_dir=AttachFile.getAttachDir(self.request,pagename,create=1)
        kw['src']=AttachFile.getAttachUrl(pagename, file_name,self.request)


        file="%(attach_dir)s/%(file_name)s" %{
             "attach_dir":attach_dir,
             "file_name":file_name}

        if not os.path.isfile(file):

            cmd="pygantt --renderer=%(renderer)s %(txt)s - >  '%(file)s'" %{
                "renderer":kw['renderer'],
                "txt":txt,
                "file":file}

            f=os.popen(cmd,'w')
            for line in lines:
                print >>f, line
            f.flush()

            kw['title']=kw['name']
            kw['alt']=kw['name']

        image_link=formatter.image(**kw)

        self.request.write(formatter.url(1,kw['src'])+image_link +formatter.url(0))
        return()




