#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history https://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/private/trunk/rlextra/security/test/test_pdfencryption.py

import os, sys
from reportlab.test import unittest
from reportlab.test.utils import SecureTestCase
from reportlab.pdfgen import canvas
from rlextra.utils import pdfencrypt


def makedoc(fileName="encrypted.pdf", userPass="User", ownerPass="Owner"):
    """
    Creates a simple encrypted pdf.
    """
    encrypt = pdfencrypt.StandardEncryption(userPass, ownerPass)
    encrypt.setAllPermissions(0)
    encrypt.canPrint = 1

    c = canvas.Canvas(fileName)
    c._doc.encrypt = encrypt

    c.drawString(100, 500, "hello world")

    c.save()
    print "wrote '%s', owner password is '%s' and user password is '%s'" %(fileName, userPass, ownerPass)

def parsedoc(fileName="encrypted.pdf", userPass="User"):
    """
    Using PDFParseContext object from Pagecatcher module to check for encryption.
    """
    from rlextra.pageCatcher.pageCatcher import PDFParseContext
    try:
        pdfContent = open(fileName, 'rb').read()
        p = PDFParseContext(pdfContent, prefix="PageForms")
        p.parse()
        if p.encrypt:
            print "Document '%s' is encrypted!" %fileName
        else:
            print "Document '%s' is not encrypted!" %fileName
    except ValueError:
        print "Document '%s' is corrupted!" %fileName



class ManualTestCase(SecureTestCase):
    "Runs manual encrypted file builders."

    def test0(self):
        makedoc()
        parsedoc()


def makeSuite():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(ManualTestCase))
    return suite


if __name__ == "__main__":
    unittest.TextTestRunner().run(makeSuite())
