#!/usr/bin/env kross

import os, sys, re, types, string, datetime, urllib

# import the reportlab module.
import reportlab
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import A0,A1,A2,A3,A4,A5,A6,B0,B1,B2,B3,B4,B5,B6,letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus.paragraph import Paragraph
from reportlab.platypus.flowables import PageBreak, Spacer
from reportlab.platypus.frames import Frame
from reportlab.lib.enums import TA_LEFT,TA_CENTER,TA_RIGHT,TA_JUSTIFY
#from reportlab.pdfgen import canvas
#from reportlab.lib import colors
#from reportlab.platypus.flowables import Flowable, Preformatted, Image, KeepTogether
#from reportlab.platypus.tableofcontents import TableOfContents
#from reportlab.platypus.xpreformatted import XPreformatted
#from reportlab.platypus.tables import TableStyle, Table

# import the kross module.
import Kross

class MyConfig:
    def __init__(self):
        self.showDialog = True
        #self.showDialog = False

        #self.readOdfFile = ""
        #self.readOdfFile = "/home/kde4/odf/_works/Lists_bulletedList/testDoc/testDoc.odt"
        self.readOdfFile = "/home/kde4/odf/_works/textFormatting_alignment/testDoc/testDoc.odt"
        #self.readOdfFile = "/home/kde4/odf/_works/Paragraph_AttributedText/testDoc/bold.odt"
        #self.readOdfFile = "/home/kde4/odf/_works/textFormatting_fontSize/testDoc/testDoc.odt"

        #self.writeFileName = ""
        self.writeFileName = "/home/kde4/__MyReportLabTest.pdf"

        self.pageSize = A4 # [width,height]
        #self.pageMargin = [ 2.0, 2.0, 2.0, 2.0 ] # [left,top,width,height]
        self.pageCompression = 1 # 0=No compression, 1=Enable compression

        self.templateName = "DefaultTemplate"

class MyTemplates:

    class _AbstractTemplate( BaseDocTemplate ):
        _invalidInitArgs = ('pageTemplates',)
        def __init__(self, writer):
            self.writer = writer
            self.config = writer.config
            self.kwdoc = writer.kwdoc
            apply(BaseDocTemplate.__init__, (self, self.config.writeFileName), )
        def onPage(self, canvas, doc):
            print "..onPage PageNumber=%s" % canvas.getPageNumber()
            if not hasattr(self,"_title"):
                self._title = self.kwdoc.documentInfoTitle()
                if not self._title:
                    self._title = self.kwdoc.documentInfoSubject()
                    if not self._title:
                        self._title = self.kwdoc.url()
            if not hasattr(self,"_author"):
                self._author = self.kwdoc.documentInfoAuthorName()
                company = self.kwdoc.documentInfoCompanyName()
                mail = self.kwdoc.documentInfoEmail()
                if company:
                    if self._author:
                        self._author = "%s, %s" % (company, self._author)
                    else:
                        self._author = company
                if mail:
                    if self._author:
                        self._author = "%s, %s" % (self._author, mail)
                    else:
                        self._author = mail
            #canvas.addOutlineEntry(title, key, level=0, closed=None)
            #canvas.setTitle(title)
            #canvas.setSubject(subj)
            #canvas.setAuthor()
            canvas.setPageCompression(self.config.pageCompression)
            #canvas.pageHasData()
            #canvas.showOutline()
            #canvas.bookmarkPage(name)
            #canvas.bookmarkHorizontalAbsolute(name, yhorizontal)
            #canvas.linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None, **kw)
            #canvas.linkRect(contents, destinationname, Rect=None, addtopage=1, relative=1, name=None, **kw)
            #canvas.addLiteral()
            #canvas.stringWidth(self, text, fontName, fontSize, encoding=None)
            #canvas.setPageTransition(self, effectname=None, duration=1, direction=0,dimension='H',motion='I')
        def onPageEnd(self, canvas, doc):
            print "..onPageEnd PageNumber=%s" % canvas.getPageNumber()
        def afterFlowable(self, flowable):
            print "..afterFlowable %s" % flowable.__class__.__name__

    class DefaultTemplate( _AbstractTemplate ):
        #name = "The default template"

        def __init__(self, writer):
            MyTemplates._AbstractTemplate.__init__(self, writer)
            (x,y,width,height) = (2.0*cm, 2.0*cm, 15.0*cm, 25.0*cm)
            mainFrame = Frame(x, y, width, height, id='MainFrame')
            page = PageTemplate('normal', [mainFrame,], self.onPage, self.onPageEnd)
            self.addPageTemplates(page)

        def onPage(self, canvas, doc):
            canvas.saveState()
            MyTemplates._AbstractTemplate.onPage(self, canvas, doc)

            # header
            if self._title:
                canvas.setFont('Times-Roman', 12)
                canvas.drawString(2.0*cm, self.config.pageSize[1] - 1.2*cm, self._title)
            if self._author:
                canvas.setFont('Times-Roman', 10)
                canvas.drawString(2.0*cm, self.config.pageSize[1] - 1.2*cm - 14.0, self._author)
            canvas.line(2.0*cm, self.config.pageSize[1] - 2.0*cm, self.config.pageSize[0] - 2.0*cm, self.config.pageSize[1] - 2.0*cm)

            # footer
            canvas.line(2.0*cm, 2.0*cm, self.config.pageSize[0]-2.0*cm, 2.0*cm)
            #if hasattr(canvas, 'headerLine'): # hackish
            #    headerline = string.join(canvas.headerLine, ' \215 ') # bullet
            #    canvas.drawString(2*cm, self.config.pageSize[1]-1.75*cm, headerline)
            canvas.setFont('Times-Roman', 8)
            canvas.drawString(2.0*cm, 1.65*cm, self.config.writeFileName)
            canvas.drawString(2.0*cm, 1.65*cm - 10.0, datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
            canvas.setFont('Times-Roman', 12)
            pageNumber = canvas.getPageNumber()
            canvas.drawString(4.0*inch, 1.0*cm, "%d" % pageNumber)

            canvas.restoreState()

        def afterFlowable(self, flowable):
            MyTemplates._AbstractTemplate.afterFlowable(self, flowable)
            if flowable.__class__.__name__ == 'Paragraph':
                f = flowable
                #(name7,name8) = (f.style.name[:7],f.style.name[:8])
                print "   style.name=%s" % f.style.name
                ## Build a list of heading parts. So far, this is the *last* item on the *previous* page...
                #if name7 == 'Heading' and not hasattr(self.canv, 'headerLine'): self.canv.headerLine = []
                #if name8 == 'Heading0': self.canv.headerLine = [f.text] # hackish
                #e
lif name8 == 'Heading1':
                    #if len(self.canv.headerLine) == 2: del self.canv.headerLine[-1]
                    #elif len
(self.canv.headerLine) == 3:
                        #del self.canv.headerLine[-1]
                        #del self.canv.headerLine[-1]
                    #self.canv.headerLine.append(f.text)
                #elif name8 == 'Heading2':
                    #if len(self.canv.headerLine) == 3: del self.canv.headerLine[-1]
                    #self.canv.headerLine.append(f.text)
                #if name7 == 'Heading':
                    ## Register TOC entries.
                    #headLevel = int(f.style.name[7:])
                    #self.notify('TOCEntry', (headLevel, flowable.getPlainText(), self.page))
                    ## Add PDF outline entries.
                    #c = self.canv
                    #title = f.text
                    #key = str(hash(f))
                    #try:
                        #if headLevel == 0: isClosed = 0
                        #else: isClosed = 1
                        #c.bookmarkPage(key)
                        #c.addOutlineEntry(title, key, level=headLevel, closed=isClosed)
                    #except ValueError: pass

class MyWriter:

    class MyParagraph:
        def __init__(self, story, reader, styles):
            self.story = story
            self.reader = reader
            