# from flask import Flask
import pdf_to_pics,feature
import os
import uuid
import platform
from flask import Flask,request,redirect,url_for,Blueprint
from werkzeug.utils import secure_filename
from sim import compute_similarity


if platform.system() == "Windows":
    slash = '\\'
else:
    platform.system()=="Linux"
    slash = '/'

UPLOAD_FOLDER = 'upload'
ALLOW_EXTENSIONS = set(['html', 'htm', 'doc', 'docx', 'mht', 'pdf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

#判断文件夹是否存在，如果不存在则创建
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
else:
    pass

# 判断文件后缀是否在列表中
def allowed_file(filename):
    return '.' in filename and \
            filename.rsplit('.', 1)[1] in ALLOW_EXTENSIONS

# 上传pdf并调用file2pic函数
@app.route('/',methods=['GET','POST'])
def upload_file():
    if request.method =='POST':
        #获取post过来的文件名称，从name=file参数中获取
        file = request.files['file']
        if file and allowed_file(file.filename):
            # secure_filename方法会去掉文件名中的中文
            filename = secure_filename(file.filename)
            # 因为上次的文件可能有重名，因此使用uuid保存文件
            file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],file_name))
            base_path = os.getcwd()
            file_path = base_path + slash + app.config['UPLOAD_FOLDER'] + slash + file_name
            print(file_path)
            return redirect(url_for('file2pic',file = file_name))
            # return redirect(url_for('test'))
            # return redirect("http://e127.0.0.1:5000/")
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Select PDF to Upload</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

# 调用pdf_to_pics.py中的类与函数，拆分图片
@app.route('/tt/<file>')
def file2pic(file):
    pics = pdf_to_pics.to_pics()
    message = pics.call_pdf2pic(file)
    print('file2pic')
    return message


# 调用sim/compute_similarity.py中的函数计算similarity
@app.route('/ttt/<path>')
def call_sim(path):
    the_similarity = compute_similarity.simi()
    message = the_similarity.similarity(path)
    print("call_sim")
    return message



# @app.route('/tttt/<alist>')
# def call_feature(alist):
#     print("call_feature")
#     the_feature = feature.feat()
#     message = the_feature.call_feature_extraction(alist)
#     # print("call_feature")
#     return message


if __name__ == "__main__":
    app.register_blueprint(pdf_to_pics.bp_2pics)

    # app.run(host='0.0.0.0', port=7000)  # IP Port
    app.run()

