#pageflow.py
"""Support for using PageCatcher within Platypus"""
import os


from reportlab.platypus.flowables import Flowable
from rlextra.pageCatcher.pageCatcher import copyPages, \
     storeFormsInMemory, restoreFormsInMemory



class LoadPdfFlowable(Flowable):
    """Imports PDF content into the current canvas when drawn.

    Used by RML2PDF, which has to store the forms itself but defer
    placing them into a document"""
    def __init__(self, pickledStuff):
        Flowable.__init__(self)
        self.pickledStuff = pickledStuff

    def drawOn(self, canvas, x, y, _sW=0):
        "This makes sure the form XObjects are loaded into the canvas"
        restoreFormsInMemory(self.pickledStuff,
                             canvas,
                             allowDuplicates=1)



class ShowPdfFlowable(Flowable):
    "draws a form xobject in absolute coordinates"
    def __init__(self, formName):
        Flowable.__init__(self)
        self.formName = formName

    def drawOn(self, canvas, x, y, _sW=0):
        #this won't do much if already loaded
        canvas.doForm(self.formName)
            



def loadPdf(filename, canvas, pageNumbers=None, prefix=None):
    if pageNumbers:
        all=0
    else:
        all=1
    if prefix is None:
        prefix = os.path.splitext(filename)[0] + '_page'
    prefix = prefix.replace('/','_')
    pdfContent = open(filename,"rb").read()
    (formNames, stuff) = storeFormsInMemory(pdfContent,
                                            pagenumbers=pageNumbers,
                                            prefix=prefix,
                                            all=1)

    if pageNumbers:
        namesToInclude = []
        for num in pageNumbers:
            namesToInclude.append(formNames[num])
    else:
        namesToInclude = None
    print 'loaded %d pages in %d bytes:' % (len(formNames), len(stuff))
    restoreFormsInMemory(stuff, canvas,
                         allowDuplicates=1,
                         verbose=1,
                         formnames=namesToInclude)
    return formNames

def test():
    #check for chaos on repeated use
    import reportlab.rl_config
    reportlab.rl_config.invariant = 1
    
    from reportlab.pdfgen.canvas import Canvas
    c = Canvas('pageflow1.pdf')
    loadPdf("test/ir684.pdf", c)
    c.setFont("Helvetica", 36)
    c.drawString(100,700, "Test restore forms")
    c.showPage()
    c.doForm("test_ir684_page0")
    c.showPage()
    c.doForm("test_ir684_page1")
    c.save()
    print 'saved pageflow1.pdf'
    print'\n'*5

    c = Canvas('pageflow2.pdf')
    loadPdf("test/ir684.pdf", c)
    loadPdf("test/ir684.pdf", c)
    c.setFont("Helvetica", 36)
    c.drawString(100,700, "Test restore forms")
    c.showPage()
    c.doForm("test_ir684_page0")
    c.showPage()
    c.doForm("test_ir684_page1")
    c.save()
    print 'saved pageflow2.pdf'

    print'\n'*5
    c = Canvas('pageflow3.pdf')
    loadPdf("test/ir684.pdf", c, pageNumbers=[0])
    loadPdf("test/ir684.pdf", c, pageNumbers=[1])
    c.setFont("Helvetica", 36)
    c.drawString(100,700, "Test restore forms")
    c.showPage()
    c.doForm("test_ir684_page0")
    c.showPage()
    c.doForm("test_ir684_page1")
    c.save()
    print 'saved pageflow3.pdf'

    
if __name__=='__main__':
    test()