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

import os
import sys
from tqdm import tqdm
from PyPDF3 import PdfFileReader, PdfFileWriter
from pdf_cr import pdf_decrypt
import time
import py_load


def pdf_compress(file_path, compass_path, password=None):
    """
    compress the pdf
    """
    pdf_reader = pdf_decrypt(file_path, password)

    if pdf_reader is None:
        return
    if pdf_reader.isEncrypted:
        print('File is encrypted, use password to operate!')

    #if not file_path.startswith('/'):
        #file_path = '{}/{}'.format(os.path.dirname(os.path.realpath(__file__)), file_path)

    #if not compass_path.startswith('/'):
        #compass_path = '{}/{}'.format(os.path.dirname(os.path.realpath(__file__)), compass_path)

    print("Compressor starts with [{}].".format(file_path))
    if not os.path.isfile(file_path):
        print("[{}] is not a file.".format(file_path))
        return

    original_file_size = os.path.getsize(file_path)

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

    if os.path.isfile(compass_path):
        print("Failed to compress the original file...")
        return

    # with open(file_path, 'rb') as original_file:
    #     with open(compass_path, 'wb') as compass_file:
    #         compass_file.write(original_file.read())

    # reader = PdfFileReader(open(file_path, 'rb'))
    writer = PdfFileWriter()

    # count page num of process
    pdf_pages = pdf_reader.getNumPages()

    # loading above process bar of process
    max_steps = pdf_pages
    process_bar = py_load.ShowProcess(max_steps)

    for i in range(pdf_pages):
        original_page = pdf_reader.getPage(i)
        original_page.compressContentStreams()
        writer.addPage(original_page)

        # 显示进度
        # print(process_bar.i)
        # print(process_bar.max_steps)
        process_bar.show_process()
        sys.stdout.flush()
        time.sleep(0.02)

    writer.write(open(compass_path, 'wb'))
    # usr oral password
    writer.encrypt(user_pwd=password, owner_pwd="", use_128bit=True)

    # Process bar close
    process_bar.close()
    process_bar.max_steps = 0

    compressed_file_size = os.path.getsize(compass_path)

    print("Compressor ends with [{}].".format(compass_path))
    print("Original File size:{:,}KB".format(int(original_file_size / 1024)))
    print("Compressed File size:{:,}KB".format(int(compressed_file_size / 1024)))
    return


if __name__ == '__main__':
    pass
