#!/usr/bin/python
"""
Just a hack to convert rst to xml and then docbook . 
May not containt all the required elements of a docbook .
Just done to make it run for the specific rst for our 
sees documentation.
"""
import xml.etree.ElementTree as ET
import os 
import re
import subprocess
import os
import pkg_resources
import glob, os, re, sys
names = glob.glob('ch*.xml')
"""
chapterno=0

def convert2xml(file):
#    print folder,subfolder,file
    global chapterno
    name=file.split('/')[-1]
    name=str(chapterno)+name.split('.')[0]
#    full_file=os.path.join(folder,file)    
#    if file.endswith('.rst'):    
    print file	    
    xml_file=name+'.xml'        
    command="rst2xml.py %s > %s" %(file , xml_file)
    print command        
    a=subprocess.Popen(command , shell=True)
	   	


def walk(repo):
    global chapterno
    mainfolder='/home/amit/sttp_latest/'    
    for readline in open('index.config','r').readlines():
        chapterno+=1		
        filename=mainfolder+readline
        convert2xml(filename)


"""
def convert2docbook(xml_string):
#    xml_file_obj=open(file,'r')
#    xml_string=xml_file_obj.read() 
#    xml_file_obj.close()       
    try:
        xml_string=re.sub('<strong>','<emphasis role="strong">', xml_string)   
        xml_string=re.sub('<literal_block','<programlisting>',xml_string)
        xml_string=re.sub('</literal_block>','</programlisting>',xml_string)
        xml_string=re.sub('xml:space="preserve">','',xml_string)
        xml_string=re.sub('<paragraph>' ,'<para>',xml_string)
        xml_string=re.sub('</paragraph>' ,'</para>',xml_string)  
        xml_string=re.sub('</strong>' ,'</emphasis>',xml_string)
        chapter= ET.Element("chapter")
        article=ET.SubElement(chapter,"article")
        articleinfo=ET.SubElement(article,"articleinfo")
        tree = ET.fromstring(xml_string)
        title= ET.SubElement(articleinfo,"title")   
        try:    
            title.text=tree.items()[1][1]
        except:
                pass    
        article.insert(1,tree)
        xml_string=ET.tostring(chapter)
        xml_string=re.sub('<document ids=.*">' ,'',xml_string)
        xml_string=re.sub('</document>' ,'',xml_string)
        return xml_string
#    docbook_file=file.split('.')[0]+'.docbook'
#    f=open(docbook_file,'w')
#    f.write(xml_string)
#    xml_string=None
    except :
        pass




if __name__=='__main__':
#    repo='/home/amit/sphinxvirt/review/'
#    walk(repo)
#    convert(1,2,3)
    for name in names:
        print name        
        xml_string=open(name,'r').read()
         
        xml_string=convert2docbook(xml_string)
        docbook_file=name.split('.')[0]+'.docbook'
        f=open(docbook_file,'w')
        try:        
            f.write(xml_string)
        except:
                pass
































