import os
from datetime import datetime
from flask import current_app, jsonify, request
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask_jwt_extended import ( jwt_required, get_jwt_identity )
from werkzeug.utils import secure_filename
from application.config import config
from application.signal_manager import signalManager
from models.app import  postAppSchema, deleteAppSchema, getListAppSchema, getListAppsSchema, getAppSchema, putAppSchema
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result

class AppResourceList(Resource):
    def __init__(self):
        pass
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser = RequestParser()

    def get(self):
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser.add_argument("page", type=int, location="args", default=1)
        # self.parser.add_argument("pageSize", type=int, location="args", default=15)
        # args = self.parser.parse_args()

        try:
            json_payload = request.json
            logger.warn(json_payload)
            data = getListAppSchema.load(json_payload)
            result = signalManager.actionGetListApp.emit(data)
            json_dumps = getListAppSchema.dump(result)
            if result:
                json_dumps = getListAppsSchema.dump(result.items)
                logger.warn(json_dumps)
                return response_result(ResponseCode.HTTP_SUCCESS, data=json_dumps, count=result.total)
            return response_result(ResponseCode.HTTP_NOT_FOUND)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)

    @jwt_required(locations=["headers"])
    def post(self):
        try:
            jwt = get_jwt_identity()

            # 获取request.files参数
            json_payload = request.json
            params = postAppSchema.load(json_payload)

            now_str = datetime.now().strftime("%Y%m%d%H%M%S")
            # 获取相对路径
            dirname = "{}-{}-{}-{}".format(params["app_name"], params["app_version"], params["category"], now_str)
            relative_path = os.sep.join([config.EPK_DIR, dirname])
            # 获取最终存储的绝对路径
            upload_path = os.path.normpath(os.sep.join([config.UPLOAD_ROOT_DIR, relative_path]))

            if not os.path.exists(upload_path):
                os.makedirs(upload_path)

            files = []
            # 应用logo
            logo = request.files.get("logo")
            if logo:
                filename = secure_filename(logo.filename)
                file_path = os.sep.join([upload_path, filename])
                file_path = os.path.normpath(file_path)
                logo.save(file_path)
                params.update({ "app_icon": file_path })

            # 应用源文件
            fileList = request.files.getlist('fileList')
            if fileList:
                upload_path = os.sep.join([upload_path, "src"])
                if not os.path.exists(upload_path):
                    os.mkdir(upload_path)

                for f in fileList:
                    filename = secure_filename(f.filename)
                    file_path = os.sep.join([upload_path, filename])
                    file_path = os.path.normpath(file_path)
                    f.save(file_path)
                    files.append(file_path)

            # obj = dict()
            # obj['filename'] = binfile.filename
            # obj['content'] = binfile.stream.read()

            params.update({ "fileList": files, "epk_path": upload_path })
            result, message = signalManager.actionPostApp.emit(params, jwt)
            if result:
                logger.warn(result)
                return response_result(ResponseCode.HTTP_SUCCESS, data=result, msg=message)
            return response_result(message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)


class AppResource(Resource):
    def __init__(self):
        pass
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser = RequestParser()

    @jwt_required(locations=["headers"])
    def get(self, uuid):
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser.add_argument("page", type=int, location="args", default=1)
        # self.parser.add_argument("pageSize", type=int, location="args", default=15)
        # args = self.parser.parse_args()

        try:
            json_payload = request.json
            print("========>", uuid, json_payload)
            data = getAppSchema.load(json_payload)
            result, message = signalManager.actionGetApp.emit(uuid, data)
            if result:
                json_dumps = getAppSchema.dump(result)
                return response_result(ResponseCode.HTTP_SUCCESS, data=json_dumps, msg=message)
            return response_result(ResponseCode.HTTP_NOT_FOUND)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)


    @jwt_required(locations=["headers"])
    def put(self, uuid):
        try:
            json_payload = request.json
            print("========>", uuid, json_payload)
            data = putAppSchema.load(json_payload)
            result, message = signalManager.actionPutApp.emit(uuid, data)
            if result:
                return response_result(ResponseCode.HTTP_SUCCESS, data=result, msg=message)
            return response_result(ResponseCode.HTTP_NO_CHANGE, msg=message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)


    @jwt_required(locations=["headers"])
    def delete(self, uuid):
        try:
            json_payload = request.json
            data = deleteAppSchema.load(json_payload)
            print("========>", uuid, data, json_payload)
            result, message = signalManager.actionDeleteApp.emit(uuid)
            if result:
                return response_result(ResponseCode.HTTP_SUCCESS, data=result, msg=message)
            return response_result(ResponseCode.HTTP_NOT_FOUND, msg=message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
