import fitz
import time
import re
import os
from sim import compute_similarity
from flask import redirect,url_for,Blueprint
from PIL import Image
import math
import operator
from functools import reduce

bp_2pics = Blueprint("2pics", __name__,url_prefix="/2pics")
# 这个bp似乎没啥用，，？

class to_pics:
    def pdf2pic(self, path, pic_path):

        t0 = time.clock()
        # 使用正则表达式来查找图片
        checkXO = r"/Type(?= */XObject)"
        checkIM = r"/Subtype(?= */Image)"

        # 打开pdf
        doc = fitz.open(path)
        # 图片计数
        imgcount = 0
        lenXREF = doc._getXrefLength()
        print(lenXREF)

        # 打印PDF的信息
        print("文件名:{}, 页数: {}, 对象: {}".format(path, len(doc), lenXREF - 1))

        # 遍历每一个对象
        for i in range(1, lenXREF):
            # 定义对象字符串
            text = doc._getXrefString(i)
            isXObject = re.search(checkXO, text)
            # 使用正则表达式查看是否是图片
            isImage = re.search(checkIM, text)

            # 如果不是对象也不是图片，则continue
            if not isXObject or not isImage:
                continue
            imgcount += 1
            # 根据索引生成图像
            pix = fitz.Pixmap(doc, i)
            # 根据pdf的路径生成图片的名称
            # new_name = path.replace('\\', '_') + "_img{}.png".format(imgcount)
            new_name = "img{}.png".format(imgcount)
            new_name = new_name.replace(':', '')

            # 如果pix.n<5,可以直接存为PNG
            if pix.n < 5:
                pix.writePNG(os.path.join(pic_path, new_name))
            # 否则先转换CMYK
            else:
                pix0 = fitz.Pixmap(fitz.csRGB, pix)
                pix0.writePNG(os.path.join(pic_path, new_name))
                pix0 = None
        # 释放资源
        pix = None
        t1 = time.clock()
        print("运行时间:{}s".format(t1 - t0))
        print("提取了{}张图片".format(imgcount))
        return str(imgcount)


    def call_pdf2pic(self, file):
        # pdf路径
        path = './upload/' + file
        pic_path = path[:-4]
        # 创建保存图片的文件夹
        if os.path.exists(pic_path):
            print("文件夹已存在，请重新创建新文件夹！")
            return "already exist"
            # raise SystemExit
        else:
            os.mkdir(pic_path)
            print(pic_path)
            m = to_pics().pdf2pic(path, pic_path)
            # return m
            return redirect(url_for('call_sim',path = file[:-4]))
            # return redirect(url_for('call_sim', m=m, pic_path=pic_path))


# @bp_2pics.route('/tt/<m>/<pic_path>')
# def call_sim(m, pic_path):
#     message = app.similarity(m, pic_path)
#     print("call_sim")
#     return message

