#!/usr/bin/env python
import sys
try:
    from PyPDF2 import PdfFileReader, PdfFileWriter,PdfFileMerger
except ImportError:
    from pyPdf import PdfFileReader, PdfFileWriter

def pdf_merge(input_files, output_stream, rotation=0):
    input_streams = []
    try:
        # First open all the files, then produce the output file, and
        # finally close the input files. This is necessary because
        # the data isn't read from the input files until the write
        # operation. Thanks to
        # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
        for input_file in input_files:
            input_streams.append(open(input_file, 'rb'))
        writer = PdfFileWriter()
        for reader in map(PdfFileReader, input_streams):
            for n in range(reader.getNumPages()):
                page=reader.getPage(n)
                page.rotateClockwise(rotation)
                writer.addPage(page)
        writer.write(output_stream)
    finally:
        for f in input_streams:
            f.close()

def fileslist (directorypath):
    import glob, os
    files= glob.glob(directorypath+'/*.pdf')
    return files


def pdf_cat(input_files, outputfilename="results.pdf"):
    pdfs = input_files
    merger = PdfFileMerger()

    for pdf in pdfs:
        merger.append(PdfFileReader(pdf, 'rb'))

    merger.write(outputfilename)
    merger.close()


if __name__ == '__main__':
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    
    #pdf_cat(sys.argv[1:], sys.stdout)
    output_path=r'/home/dl92/Documents/DigitalPaper/Upload/merged.pdf'
    output_path2=r'/home/dl92/Documents/DigitalPaper/Upload/Firework Maker.pdf'
    files=fileslist(r'/home/dl92/Documents/DigitalPaper/Upload')
    files.sort()
    output_stream = open(output_path, 'wb')
    pdf_merge(files[0:5] ,output_stream,90)
    output_stream.close()

    output_stream = open(output_path2, 'wb')
    pdf_merge([output_path]+files[5:7]  ,output_stream,0)
    output_stream.close()
    #pdf_merge(fileslist(r'/home/dl92/Documents/DigitalPaper/Upload'),output_stream)
    



