##!/usr/bin/python
# -*-coding:UTF-8-*-

import os
# from PyPDF3 import PdfFileWriter
from PyPDF3 import PdfFileReader, PdfFileWriter


def formatTime(longtime):
    """
    Format the date func
    :param longtime: format the date
    :return:
    """
    import time
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(longtime))


def formatByte(number):
    """
    Format the size func
    :param number: format byte number
    :return:
    """
    for (scale, label) in [(1024 * 1024 * 1024, "GB"), (1024 * 1024, "MB"), (1024, "KB")]:
        if number >= scale:
            return "%.2f %s" % (number * 1.0 / scale, label)
        elif number == 1:
            return "1byte"
        else:
            byte = "%.2f" % (number or 0)
    return (byte[:-3] if byte.endswith(".00") else byte) + "byte"


# Pdf file encryption judgment
def pdf_decrypt(filename, password=''):
    try:
        old_file = open(filename, 'rb')
        if PdfFileReader(old_file, strict=False):
            # could rm comm to show msg
            # print('PDF File can read!')
            pass
    except Exception as err:
        print('PDF File is not to open! ' + str(err))
        return None

    # create read object
    pdf_reader = PdfFileReader(old_file, strict=False)

    # decrypte opteration
    if pdf_reader.isEncrypted:
        print("PDF file need password!")
        try:
            if password is None:
                print('%s is encrypted，need password.' % filename)
                print("\nPlease enter the file password.")
                return None
            elif pdf_reader.decrypt(password) != 1:
                print('%s password is incorrect!' % filename)
                print("Processing stop!")
                return None
            else:
                print("PDF Password is correct!")

        except Exception as err:
            # not support pdf algorithm progress.
            print('Decryption failed! ' + str(err))
            return None
    else:
        # could rm comm to show msg
        # print("The document does not require a password.")
        pass

    if old_file in locals():
        old_file.close()

    return pdf_reader


def pdf_info(filename, password=''):
    """
    get pdf info
    :param filename: the oral pdf file
    :param password: file's user password,default is none
    :param dec_filename: new pdf file name after decrypt
    :return:
    """

    # create a Reader
    print('Getting file information ...')
    # pdf_reader = PdfFileReader(filename, strict=False)
    # get PdfFileReader object
    pdf_reader = pdf_decrypt(filename, password)

    if pdf_reader is None:
        return
    else:
        print("================================")
        fileinfo = os.stat(filename)  # get file base info.
        print("File full path", os.path.abspath(filename))  # get file path
        # output file sys info.
        print("Index number:", fileinfo.st_ino)
        print("Dev name:", fileinfo.st_dev)
        print("File size:", formatByte(fileinfo.st_size))
        print("Last visit:", formatTime(fileinfo.st_atime))
        print("Last modified:", formatTime(fileinfo.st_mtime))
        print("Time of last state change:", formatTime(fileinfo.st_ctime))
        print("================================")
        # get pdf file document info.
        documentInfo = pdf_reader.getDocumentInfo()
        print('documentInfo = %s' % documentInfo)
        # get page layout
        pageLayout = pdf_reader.getPageLayout()
        print('pageLayout = %s ' % pageLayout)
        # get page mode
        pageMode = pdf_reader.getPageMode()
        print('pageMode = %s' % pageMode)
        xmpMetadata = pdf_reader.getXmpMetadata()
        print('xmpMetadata = %s ' % xmpMetadata)
        # get pdf pages number
        pageCount = pdf_reader.getNumPages()
        print('pageCount = %s' % pageCount)
        pdfdecrypt = pdf_reader.isEncrypted
        print('pdf decrypt = %s ' % pdfdecrypt)
        nDestinations = pdf_reader.namedDestinations
        print('Name destinations = %s ' % nDestinations)


# Decrypt pdf and Remove Pdf password to new file.
def pdf_rmpw(filename, password, dec_filename=None):
    """
    Put the encrypt file to decrypt, create a new pdf file without password.
    :param filename: the oral encrypt pdf file
    :param password: it's oral password
    :param dec_filename: new pdf file name after decrypte.
    :return:
    """

    # create reader and writer object

    pdf_reader = pdf_decrypt(filename, password)

    if pdf_reader is None:
        return
    if not pdf_reader.isEncrypted:
        print('File is not encrypted, no need to operate!')
        return

    print("Please wait,The Encrypted pdf is to be Decrypt")

    pdf_writer = PdfFileWriter()

    pdf_writer.appendPagesFromReader(pdf_reader)

    if dec_filename is None:
        dec_filename = "".join(filename[:-4]) + '_' + 'decrypted' + '.pdf'
    if not dec_filename.lower().endswith(".pdf", 0, len(dec_filename)):
        dec_filename = dec_filename + '.pdf'

    print(filename)
    print(dec_filename)

    # write a new file
    pdf_writer.write(open(dec_filename, 'wb'))
    print("Decrypt successfully.No password PDF \"%s\" generated!" % dec_filename)


def pdf_getpw(filename, enc_filename, password):
    """
    put the pdf encrype.
    :param filename: pdf file to be decrypt
    :param dec_filename: the pdf flie name after encrypt.
    :param password: it's new password
    :return:
    """
    # create Reader and  Writer object
    pdf_reader = pdf_decrypt(filename, password)

    if pdf_reader is None:
        print('File is encrypted, no need to operate!')
        return
    if not pdf_reader.isEncrypted:
        print('Please wait ... start encryption!')
        pdf_writer = PdfFileWriter()

        pdf_writer.appendPagesFromReader(pdf_reader)
        pdf_writer.encrypt(user_pwd=password, owner_pwd="", use_128bit=True)

        if enc_filename is None:
            enc_filename = "".join(filename[:-4]) + '_' + 'encrypted' + '.pdf'
        if not enc_filename.lower().endswith(".pdf", 0, len(enc_filename)):
            enc_filename = enc_filename + '.pdf'

        print(filename)
        print(enc_filename)

        # write a new file
        pdf_writer.write(open(enc_filename, 'wb'))

        print("Encrypted successfully. \"%s\" generated!" % enc_filename)


if __name__ == "__main__":
    pass
