from backstage.config import UPLOAD_PATH_MAP
import os
import shutil
from flask import render_template, Blueprint, request, redirect, url_for
import flask
from flask_cors import CORS, cross_origin
from flask.helpers import make_response, send_file, send_from_directory
from werkzeug.wrappers import Response
import requests
from PIL import Image, ImageFile
from urllib.parse import urlparse
import uuid
import json
from backstage.config import PORTAL_SERVER

ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None

#from backstage.utils.routes import update_manage_table

upload_app = Blueprint('upload', __name__)


@upload_app.route('/backstage/test/<path:iurl>', methods=['GET'])
def upload_test(iurl):

    test = iurl[0:iurl.rfind("/")+1]
    new_response = requests.get(PORTAL_SERVER + 'contents?url=' + test)
    #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
    for key, value in json.loads(new_response.content.decode('utf-8'))[0].items():
        if key == 'path':
            print(value.replace('\\', '/'))
    # print(my_dict[0].items())
    return new_response.content

@upload_app.route('/backstage/multiupload/<path:iurl>', methods=['POST']) #collections
def upload_multi_post(iurl):

    # 取得md路徑
    mdPath = ""
    new_response = requests.get(PORTAL_SERVER + 'contents?url=' + iurl)
    #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
    obj = json.loads(new_response.content.decode('utf-8'))
    
    if len(obj) > 0:
        for key, value in obj[0].items():
            if key == 'path':
                mdPath = value.replace('\\', '/')
                #print(mdPath)
                mdPath = mdPath[0:mdPath.rfind('/')+1]
                #print(mdPath)
    isProduct = False
    if mdPath.find("設計家具") >= 0 or mdPath.find("模組系統櫃") >= 0:
        isProduct = True
    #bdata = request.stream.read()
    filepath = ""
    itype = ""
    print("markdown path is" + mdPath)
    #aa = request.get_data()
    if iurl == "title":
        itype = iurl
        filepath = iurl
    else:
        itype = iurl[0:iurl.find("/")]
        filepath = iurl[iurl.rfind("/")+1:]

    if request.method == 'POST':

        # check if the post request has the file part
        # print(request.full_path)
        """ if 'file' not in request.files:
            #flash('No file part')
            return redirect(request.url) """
        print(request.files)
        print(len(request.files))
        if len(request.files) == 0:
            aa = {"success": 0}
            return aa
        else:
            n=0
            filelink = ''
            for i in request.files:
                n+=1
                fname = 'image' + str(n)
                file = request.files[fname]
                print("The file is at" + filepath)

                # If the user does not select a file, the browser submits an
                # empty file without a filename.
                """ if file.filename == '':
                    #flash('No selected file')
                    return redirect(request.url) """
                oimgtype = file.filename[file.filename.rfind(".")+1:]
                oimgtypeName = oimgtype
                if oimgtype.lower() == 'jpg':
                    oimgtypeName = 'jpeg'

                if file and not isProduct:
                    #filename = secure_filename(file.filename)

                    #fname = str(uuid.uuid4()) + file.filename[file.filename.rfind("."):]
                    #sitepath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "/img/"
                    if filepath == "title":
                        sitepath = UPLOAD_PATH_MAP[0][2] + "/static/img/title/"
                    else:
                        sitepath = mdPath + "/img/"
                        #sitepath = UPLOAD_PATH_MAP[0][0] + "../" + itype + "/" + filepath + "/img/"

                    wfname = str(uuid.uuid4()).replace('-','') + ".webp"
                    owfname = wfname.replace('webp', oimgtype)
                    #fullpath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "\\img\\" + fname
                    #print(UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind("/")+1:] + "/img/" + fname)
                    # file.save(fullpath)
                    #image_object = Image.open(fullpath)
                    #print(request.args.get('url', type=str))
                    wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
                    owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
                    print("1wpath is " + wpath)
                    print("1owpath is " + owpath)
                    #fullpath = wpath + fname
                    if not os.path.exists(wpath):
                        os.makedirs(wpath)
                    if not os.path.exists(owpath):
                        os.makedirs(owpath)
                    if not os.path.exists(sitepath):
                        os.makedirs(sitepath)
                    # file.save(fullpath)
                    image_object = Image.open(file)
                    image_object.save(owpath+owfname)
                    if image_object.size[0] > 1000:
                        image_object.thumbnail(size=((1600, 1600)))
                    image_object.save(wpath+wfname)
                    image_object.save(sitepath+wfname)
                    print("Loc1a: " + wpath+wfname)
                    print("Loc1b: " + owpath+wfname)
                    print("Loc2: " + sitepath+wfname)
                    print(filepath)
                    #file.save(os.getcwd()+ "/backstage/upload/img/"+ fname)
                    # return redirect(url_for('download_file', name=file.filename))
                    filelink += wfname + ";;;"
            print(filelink)
            aa = {"success": 1, "fileurl": filelink}
            return aa

        if request.method == 'GET':
            print('GET')
            # print(request.files)
            # print(request.form)

        # print(requests.post("/backstage/upload"))
        aa = {"success": 1, "file": {"url": "http://www.choozmo.com/images/logo%20%281%29.webp", }}
        return aa

@upload_app.route('/backstage/upload/<path:iurl>', methods=['POST'])
def upload_post(iurl):

    # 取得md路徑
    mdPath = ""
    new_response = requests.get(PORTAL_SERVER + 'contents?url=' + iurl)
    #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
    obj = json.loads(new_response.content.decode('utf-8'))
    
    if len(obj) > 0:
        for key, value in obj[0].items():
            if key == 'path':
                mdPath = value.replace('\\', '/')
                #print(mdPath)
                mdPath = mdPath[0:mdPath.rfind('/')+1]
                #print(mdPath)
    print(mdPath)
    isProduct = False
    if mdPath.find("設計家具") >= 0 or mdPath.find("模組系統櫃") >= 0:
        isProduct = True
    #bdata = request.stream.read()
    filepath = ""
    itype = ""
    print(mdPath)
    #aa = request.get_data()
    if iurl == "title":
        itype = iurl
        filepath = iurl
    else:
        itype = iurl[0:iurl.find("/")]
        filepath = iurl[iurl.rfind("/")+1:]

    if request.method == 'POST':

        # check if the post request has the file part
        # print(request.full_path)
        """ if 'file' not in request.files:
            #flash('No file part')
            return redirect(request.url) """
        if len(request.files) == 0:
            aa = {"success": 0}
            return aa
        else:
            file = request.files['image']
            #file2 = request.files['image2'] #again, reference
            print("The file is at" + filepath)

            # If the user does not select a file, the browser submits an
            # empty file without a filename.
            """ if file.filename == '':
                #flash('No selected file')
                return redirect(request.url) """
            oimgtype = file.filename[file.filename.rfind(".")+1:]
            oimgtypeName = oimgtype
            if oimgtype.lower() == 'jpg':
                oimgtypeName = 'jpeg'

            if file and not isProduct:
                #filename = secure_filename(file.filename)

                #fname = str(uuid.uuid4()) + file.filename[file.filename.rfind("."):]
                #sitepath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "/img/"
                if filepath == "title":
                    sitepath = UPLOAD_PATH_MAP[0][2] + "/static/img/title/"
                else:
                    sitepath = mdPath + "/img/"
                    #sitepath = UPLOAD_PATH_MAP[0][0] + "../" + itype + "/" + filepath + "/img/"

                wfname = str(uuid.uuid4()).replace('-','') + ".webp"
                owfname = wfname.replace('webp', oimgtype)
                #fullpath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "\\img\\" + fname
                #print(UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind("/")+1:] + "/img/" + fname)
                # file.save(fullpath)
                #image_object = Image.open(fullpath)
                #print(request.args.get('url', type=str))
                wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
                owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
                print("1wpath is " + wpath)
                print("1owpath is " + owpath)
                #fullpath = wpath + fname
                if not os.path.exists(wpath):
                    os.makedirs(wpath)
                if not os.path.exists(owpath):
                    os.makedirs(owpath)
                if not os.path.exists(sitepath):
                    os.makedirs(sitepath)
                # file.save(fullpath)
                image_object = Image.open(file)
                image_object.save(owpath+owfname)
                if image_object.size[0] > 1000:
                    image_object.thumbnail(size=((1600, 1600)))
                image_object.save(wpath+wfname)
                image_object.save(sitepath+wfname)
                print("Loc1a: " + wpath+wfname)
                print("Loc1b: " + owpath+wfname)
                print("Loc2: " + sitepath+wfname)
                print(filepath)
                #file.save(os.getcwd()+ "/backstage/upload/img/"+ fname)
                # return redirect(url_for('download_file', name=file.filename))
                aa = {"success": 1, "file": {"url": "/backstage/upload/" +
                                             filepath+"/img/" + wfname, "width": image_object.width, "height": image_object.height}}
                # aa = {"success": 1, "file": {"url": UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind(
                #    "/")+1:] + "/img/" + fname, "width": image_object.width, "height": image_object.height}}
                return aa
            elif isProduct:
                wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
                print("2wpath is " + wpath)
                wfname = str(uuid.uuid4()) + ".webp"
                image_object = Image.open(file)
                #image_object.save(mdPath+wfname, oimgtypeName)
                if image_object.size[0] > 1000:
                    image_object.thumbnail(size=((1600, 1600)))
                if not os.path.exists(wpath):
                    os.makedirs(wpath)
                image_object.save(wpath+wfname)
                image_object.save(mdPath+wfname)
                print("Loc3: " + wpath+wfname)
                print("Loc4: " + mdPath+wfname)
                owfname = wfname.replace('webp', oimgtype)
                aa = {"success": 1, "file": {"url": "/backstage/upload/" + filepath+"/img/" + wfname,
                                             "width": image_object.width, "height": image_object.height}}
                return aa
        if request.method == 'GET':
            print('GET')
            # print(request.files)
            # print(request.form)

        # print(requests.post("/backstage/upload"))
        aa = {"success": 1, "file": {"url": "http://www.choozmo.com/images/logo%20%281%29.webp", }}
        return aa


@upload_app.route('/backstage/upload/<path:filepath>', methods=['GET'])
def upload_get(filepath):
    # print(filepath)
    #print(os.getcwd() + "/backstage/upload/"+filepath, filepath[filepath.rfind("/")+1:])
    #aa = {"success" : 1,"file": { "url" : "https://www.tesla.com/tesla_theme/assets/img/_vehicle_redesign/roadster_and_semi/roadster/hero.jpg", } }
    # return redirect(url_for('upload.upload_get',filename=filename), code=301)
    # return send_from_directory(os.getcwd() + "/backstage/upload/"+filepath, filepath[filepath.rfind("/")+1:])

    return send_file(os.getcwd() + "/backstage/upload/"+filepath)


@upload_app.route('/backstage/getimage/<path:iurl>', methods=['POST', 'GET'])
def get_image(iurl):

    itype = iurl[0:iurl.find("/")]
    filepath = iurl[iurl.rfind("/")+1:]

    # print(request.get_json()['url'])
    if itype == "blog":
        sitepath = UPLOAD_PATH_MAP[0][0] + "../blog/" + filepath + "/img/"
    else:
        sitepath = UPLOAD_PATH_MAP[0][0] + filepath + "/img/"
    #sitepath = UPLOAD_PATH_MAP[0][0] + filepath + "/img/"
    oimgtype = str(request.get_json()['url'])[str(request.get_json()['url']).rfind(".")+1:]
    oimgtypeName = oimgtype
    if oimgtype.lower() == 'jpg':
        oimgtypeName = 'jpeg'
    # fname = str(uuid.uuid4()) + str(request.get_json()
    #                                ['url'])[str(request.get_json()['url']).rfind("."):]
    wfname = str(uuid.uuid4()) + ".webp"
    owfname = wfname.replace('webp', oimgtype)
    wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
    owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
    """ fullpath = wpath + fname
    if not os.path.exists(wpath):
        os.makedirs(wpath)
    f = open(fullpath, 'wb')
    f.write(requests.get(request.get_json()['url']).content)
    f.close() """
    if not os.path.exists(wpath):
        os.makedirs(wpath)
    if not os.path.exists(owpath):
        os.makedirs(owpath)
    if not os.path.exists(sitepath):
        os.makedirs(sitepath)
    image_object = Image.open(requests.get(request.get_json()['url'], stream=True).raw)
    image_object.save(owpath+owfname)
    if image_object.size[0] > 1000:
        image_object.thumbnail(size=((1600, 1600)))
    image_object.save(wpath+wfname)
    image_object.save(sitepath+wfname)
    # send_file()
    #aa = {"success" : 1,"file": { "url" : "http://localhost:9000/backstage/upload/avatar1.jpg", } }
    #resp = make_response(open(os.getcwd()+ "/backstage/upload/" + fname, 'br').read(), 301)
    #resp.content_type = "image/jpeg"
    #resp.content_encoding = "Unicode"
    # return redirect(request.get_json()['url'], code=301)
    aa = {"success": 1, "file": {"url": "/backstage/upload/" +
                                 filepath+"/img/" + wfname, "width": image_object.width, "height": image_object.height}}
    return aa


@upload_app.route('/backstage/modTitle/<path:filepath>', methods=['GET'])
def modify_title(filepath):
    oldPath = UPLOAD_PATH_MAP[0][0] + filepath.split('/')[0]
    newPath = UPLOAD_PATH_MAP[0][0] + filepath.split('/')[1]
    # os.renames(oldPath,newPath)
    """ if os.path.exists(newPath):
        return {"success" : 0, "message" : "New directory exists."} """
    """ shutil.copytree(oldPath, newPath)
    shutil.rmtree(oldPath) """
    print(oldPath + ' => ' + newPath)

    return {"success": 1}
