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

import io
import os
import sys
import time

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')  # set sys def-encode utf8

# import requests
PATH_FILE = __file__  # __file__全局变量获取当前文件路径
# print(a)
PATH_DIR = os.path.dirname(PATH_FILE)  # 获取文件当前目录
# print(b)
DIR_LIB = "Lib"  # 自定义文件目录名称

PATH_LIB = os.path.join(PATH_DIR, DIR_LIB)  # 将获取文件当前目录，与自定义文件目录名称，拼接成完整的路径
# print(PATH_LIB)
# print("\n")
sys.path.append(PATH_LIB)  # 将拼接好的路径，添加到解释器模块路径中

from PyPDF3 import PdfFileReader, PdfFileWriter
# utils 243 modify
import py_load


def merge_pdfs(pdf_paths, output):
    # print(pdf_paths)
    merge_fname_list = []
    merge_bookmn_list = []
    merge_fpage_list = [0, ]

    for pdf_path in pdf_paths:
        merge_fname_list.append(pdf_path.split("/")[-1])

        merge_bookmn_list.append(pdf_path.split("/")[-1].split(".")[0])
        pdf_reader = PdfFileReader(pdf_path)
        merge_fpage_list.append(pdf_reader.getNumPages())

    merge_file_name = ", ".join(merge_fname_list)
    merge_of_name = output.split("/")[-1]
    print("Will merge into file: %s" % (merge_of_name))
    print(
        "%s PDF files to be merged:\n%s\n\nMerge is in progress,please wait. " % (len(pdf_paths), merge_file_name)
    )

    currt_t = str(int(round(time.time() * 1000)))  # 不重复时间戳

    # get pdf files num
    pdf_files_num = len(pdf_paths)
    pdf_writer = PdfFileWriter()

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

    for path in pdf_paths:
        pdf_reader = PdfFileReader(path)
        # 获取 PDF 的页数
        # pagecount = pdf_reader.getNumPages()
        # pdfwriter = PdfFileWriter()

        for page in range(pdf_reader.getNumPages()):
            pdf_writer.addPage(pdf_reader.getPage(page))

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

    # Process bar close
    process_bar.close()

    merge_fbm_count = merge_fpage_list[0]
    for i in range(len(pdf_paths)):
        merge_fbm_page = merge_fpage_list[i] + merge_fbm_count
        pdf_writer.addBookmark(merge_bookmn_list[i], merge_fbm_page)
        merge_fbm_count += merge_fpage_list[i]

    try:
        # 写入合并的pdf
        with open(output, 'wb') as out:
            pdf_writer.write(out)
    except Exception as e:
        print(e)
