from pychart import *
import pychart.doc_support
import getopt
import string
import sys
import re

ftype="png"

optlist, argv = getopt.getopt(sys.argv[1:], "X", ["ps", "pdf"])
for l in optlist:
    if l[0] == "--pdf":
        ftype="pdf"
    if l[0] == "--ps":
        ftype="eps"
        

def formatDocString(str):
    str = re.sub("<<([^>]+)>>", "@xref{\\1}.", str)
    return str

def outputClassAttrs(moduleName, className):
    sys.stderr.write("MODULE=%s class=%s\n" % (moduleName, className))
    x = pychart.doc_support.modules[moduleName]
    v = x[className]
    #print "@multitable @columnfractions 0.25 0.15 0.15 0.45\n";
    #print "@item @strong{Attribute}\n@tab @strong{Type}\n@tab @strong{Default}\n@tab @strong{Description}\n";
    keys = v.keys.keys()
    keys.sort()
    for key in keys:
        if key[0] == '_':
            continue
        val = v.keys[key]
        print "@deffn Attribute ", key,
	s = pychart.doc_support.stringify_type(val[0])
	s2 = str(s)
	mm = re.match("(.*)\\.T$", s2)
        print " %s\n" % (s,),

        if len(val) > 4:
            print "Default: %s." % formatDocString(val[4]),
        else:
            print "Default: %s." % pychart.doc_support.stringify_value(val[2]),
            
        if len(val) > 3:
            sys.stderr.write("KEY=%s" % (key,) + " STR=%s\n" % (val,))
            print formatDocString(val[3])
	if mm:
	    print "@xref{%s}." % (mm.group(1),)
	print "@end deffn\n";
    #print "@end multitable";

def copy_file(src, dest):
    infp = open(src, "rb")
    outfp = open(dest, "wb")
    outfp.writelines(infp.readlines())
    infp.close()
    outfp.close()
    
nodeNames = []
nodeReplaces = []
demoDir = "../demos/"

def scanNodes(fp):
    global nodeNames
    for line in fp.readlines():
        moNode = re.match("^@node ([^,]*)", line)
        if moNode:
            nodeNames.append(re.compile("\\b(" + moNode.group(1) + ")\\b"))

def include_text_file(file):
    fp = open(file, "r")
    print "@example\n"
    for line in fp.readlines():
        line = string.expandtabs(line)
        line = re.sub("@", "@@", line)
        line = re.sub("{", "@{", line)
        line = re.sub("}", "@}", line)
        print line,
    fp.close()
    print "@end example"

def format_doc(str):
    out = ""
    empty_line_found = 0
    in_example = None
    
    for line in string.split(str, "\n"):
        if empty_line_found and len(line) > 0 and line[0] != ' ':
            if not in_example:
                out = out + "@example\n"
                in_example = 1
            out = out + line + "\n"
        else:
            if line == "":
                empty_line_found = 1
                
            if in_example:
                out = out + line + "\n@end example\n"
            else:
                out = out + line + "\n"
            in_example = None
    if in_example:
        out = out + "\n@end example\n"
    return out

fp = open(argv[0], "r")

scanNodes(fp)

fp.seek(0)

line = fp.readline()
while line != "":
    mo = re.match("^%%([^.]+)\\.(.*)", line)
    mo2 = re.match("^%-([^,]*),(.*)", line)
    mo3 = re.match("^%-(.*)", line)
    mo4 = re.match("^%#([^,]*),(.*)", line)
    mo5 = re.match("^%i(.*)", line)
    mo6 = re.match("^%d(.*)", line)

    line = re.sub("@chart\\{\\}", "PyChart", line)
    line = re.sub("@shadow{}", """Parameter @var{shadow}, if none, draws a drop-shadow.  It should be a
tuple of three values, (@var{x_off}, @var{y_off}, @var{fill}). """, line)
    
    if mo:
        print "XXX", line
        outputClassAttrs(mo.group(1), mo.group(2))
    elif mo2 or mo4:
	envname="{figure}"
	envarg = ""
	if mo4:
	    envname = "{figure}"
	    envarg = ""
	    mo2=mo4
        file=mo2.group(1)
        description=mo2.group(2)
        for ftype in ["png", "eps", "pdf"]:
            copy_file("%s%s-c.%s" % (demoDir, file, ftype),
                      "%s.%s" % (file, ftype))
            
        print "@image{%s,,}\n" % (file)
        print description, "\n"
        print "Below is the source code that produces the above chart."
        include_text_file(demoDir + file + ".py")
        
    elif mo3:
        file = mo3.group(1)
        include_text_file(demoDir + file)
    elif mo5:
        file = mo5.group(1)
        for ftype in ["png", "eps", "pdf"]:
            copy_file("%s%s-c.%s" % (demoDir, file, ftype),
                      "%s.%s" % (file, ftype))
            
        print "@image{%s,}\n" % (file)
    elif mo6:
        obj_name = mo6.group(1)
        obj = eval(obj_name)
        print format_doc(str(obj.__doc__)), "\n"
    else:
        print line,
    line = fp.readline()

