#!/usr/bin/python

## XSLT Reference
## Copyright (C) 2000 Miloslav Nic (nicmila@idoox.com)
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


import re,string,os,shutil,sys,myFunct

temp1=temp2=temp3=0          #used to pass parameters to re.sub() functions
axeslist=[]
functionlist=[]     #keeps functions and axes used in a stylesheet, used in re.sub()


def insertExampleToHTML(source,xml,xslt):
    try:
        input = open(source)
        data=input.read()
        input.close()
    except IOError: return


    global temp1,temp2
    temp1,temp2 = xml,xslt
    def aaa(match):
        global temp1, temp2
        xml,xslt=temp1,temp2
        
        frame="../OutputExamples/example_"+xml+"_"+xslt+"_frame.html"
        
        if re.compile(frame).search(match.group(1)): return match.group(0)
        id=str(int(xslt)*10000+int(xml))
        insert  = "<!--"+id+"--><a href='"+frame+"' target='_blank'>"+xslt+":"+xml+"</a>" 

        
        if not(re.compile("--\d+").search(match.group(1))):
            return "<!--AllStart-->\n"+insert+"\n<!--AllEnd-->"
        examples=string.split(match.group(1),"\n")

        inserttag=1                  
        for i  in range(len(examples)):
            r=re.compile("<!--(\d+)").match(examples[i])
            if not(r) or int(r.group(1))<int(id) : continue
            examples.insert(i,insert)
            inserttag=0
            break
        if inserttag: examples.append(insert)
            
        return  "<!--AllStart-->"+string.join(examples,"\n")+"<!--AllEnd-->"

    data=re.compile("<\!--AllStart-->(.*?)<\!--AllEnd-->",re.S).sub(aaa,data)
    output=open(source,"w")
    output.write(data)
    output.close()
  

def addExampleToIndex(file,xml,xslt):
    input=open("../WorkDir/xsltIndexes.dat")
    data=input.readlines()
    data.sort()
    input.close()

    
    dict={}
    for line in data:
        m =  re.compile("([\w-]+) ---(.*)").match(line)
        key = m.group(1)
        value= m.group(2)

        if dict.has_key(key):  dict[key]=dict[key]+value
        else: dict[key]=value

    for key  in dict.keys():
        insertExampleToHTML("../Output/xslt_"+key+".html",xml,xslt)
        lst=string.split(dict[key])     #remove superfluous attributes
        lst=myFunct.uniqueSortedList(lst)
        
        for attr in lst:
            insertExampleToHTML("../Output/xslt_"+key+"_"+attr+".html",xml,xslt)
    

def xsltFunction(match):
    global functionlist
    functionlist.append(match.group(1))
    return "<a class='function' href='../Output/function_"+match.group(1)+".html'>"+match.group(1)+"</a>("

def xsltAxis(match):
    global axeslist
    axeslist.append(match.group(1))
    return "<a class='axis' href='../Output/axis_"+match.group(1)+".html'>"+match.group(1)+"</a>::"

def xsltAttribute(match):
    strng=myFunct.htmlize(match.group(1))
    strng=re.compile("([\w-]+)::").sub(xsltAxis,strng)
    return re.compile("([\w-]+)\(").sub(xsltFunction,strng)

def xsltText(match):
    return myFunct.htmlize(match.group(1))

def processStylesheet(file,xml,xslt):
    global functionlist,axeslist
    functionlist=[]
    axeslist=[]
    input=open("../WorkDir/xslt.html")
    data=input.read()
    input.close()

    data=re.compile("XyX(.*?)YxY").sub(xsltAttribute,data)
    data=re.compile("XXTEXT(.*?)YYTEXT",re.S).sub(xsltText,data)

    functionlist=myFunct.uniqueSortedList(functionlist)
    axeslist=myFunct.uniqueSortedList(axeslist)
    
    for fun in functionlist:
        insertExampleToHTML("../Output/function_"+fun+".html",xml,xslt)

    for axis in axeslist:
        insertExampleToHTML("../Output/axis_"+axis+".html",xml,xslt)

    out=open(file,"w")
    out.write(data)
    out.close()


def processResult(file,xml,xslt):
    "postprocess file (the result of  example transformation)"
    start="example_"+str(xml)+"_"+str(xslt)
    menustart="&nbsp;&nbsp;&nbsp;<a class='menu' href='"
    input = open(file)
    data= input.read()
    input.close()
    data=myFunct.htmlize(data)

    out=open(file,"w")
    out.write("""
    <html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <link rel='stylesheet' type='text/css' href='../CSS/style.css'>
    <title>out 
    """)
    out.write(xslt+":"+xml)
    out.write("""
    </title></head><body><table width="100%" class="menu" cellspacing='0' cellpadding='0' border='0'>
    <tr><td>
    """)
    out.write(menustart+"javascript:back()'>back</a>")
    out.write(menustart+start+"_frame.html' target='_top'>all</a>")
    out.write(menustart+start+"_xml.html' target='_top'>xml</a>")
    out.write(menustart+start+"_xslt.html' target='_top'>xslt</a>")
    out.write(menustart+start+"_result.html' target='_top'>out</a>")
    out.write("</td><td class='right'><span class='menu'>")
    out.write(xslt+":"+xml+"&nbsp;&nbsp;&nbsp;")
    out.write("</span></td></tr></table>"+data+"</body></html>")
    out.close()

def processXMLsource(xml,outxml):
    input=open("../SourceXML/xml"+xml+".xml")
    data=input.read()
    input.close()
    hit=re.compile("<\!DOCTYPE.*?\]>",re.S).search(data)
    if hit:
        doctype =  hit.group(0)
        doctype = "<br>"+myFunct.htmlize(doctype) + "<br><br>"
        
        input = open(outxml)
        data=input.read()
        input.close()
        data = re.compile("<br>").sub(doctype,data,1)
        out=open(outxml,"w")
        out.write(data)
        out.close()
    
def printFrame(xml,xslt):
    "print main example frame"
    start="example_"+str(xml)+"_"+str(xslt)
    out=open("../OutputExamples/"+start+"_frame.html","w")
    out.write("<html><head><title>Example ")
    out.write(xslt+":"+xml)
    out.write("</title></head><frameset cols='50%,*'>")
    out.write("<frame name='xslt' src='"+start+"_xslt.html'>")
    out.write("<frameset rows='50%,*'>")
    out.write("<frame name='xml' src='"+start+"_xml.html'>")
    out.write("<frame name='result' src='"+start+"_result.html'>")
    out.write("</frameset></frameset></html>")
    out.close()


def runExample(xml,xslt):
    for x in xslt:
        x,xml=str(x),str(xml)
        outresult="../OutputExamples/example_"+xml+"_"+x+"_result.html"
        outxml="../OutputExamples/example_"+xml+"_"+x+"_xml.html"
        outxslt="../OutputExamples/example_"+xml+"_"+x+"_xslt.html"
        outframe="../OutputExamples/example_"+xml+"_"+x+"_frame.html"
        inxml="../SourceXML/xml"+xml+".xml"
        inxsl="../SourceXSLT/xslt"+x+".xslt"

        if not(os.path.exists(outresult)):
            os.system("saxon -o "+outresult+" "+inxml+" "+inxsl)
            processResult(outresult,xml,x)
    
        if not(os.path.exists(outxml) and os.path.exists(outxslt)):
            shutil.copyfile(inxsl,"../WorkDir/xslt.xslt")  #needed for transformation with example.xslt
            os.system("saxon -o "+outxml+" "+inxml+" ../XSLT/example.xslt xml="+xml+" xslt="+x)
            processStylesheet(outxslt,xml,x)
            addExampleToIndex(inxsl,xml,x)
            processXMLsource(xml,outxml)
      
        if not(os.path.exists(outframe)):
            printFrame(xml,x)

    
###############################################################

def run():
    data=open("../Data/exampleIndex.dat").readlines()
    for row in data:
        if re.compile("\s*#").match(row): continue
        if not(re.compile("\d").match(row)): break
        find = re.compile("(\d+):([\d ]+)").search(row)
        print row
        xml=find.group(1)
        xslt=string.split(find.group(2))
        runExample(xml,xslt)


run()

os.system("python exampleOverview.py")

    






