'''
Author: your name
Date: 2021-07-15 09:33:39
LastEditTime: 2021-07-27 16:41:32
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\build_out\views\package.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import os
import json
import traceback
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 application.signal_manager import signalManager
from models.package import  getListPackageSchema, getListPackagesSchema, getPackageSchema
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result

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

    @jwt_required(locations=["headers"])
    def get(self):
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        self.parser.add_argument("app", type=str, location="args", nullable=True, required=False)
        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:
            jwt = get_jwt_identity()
            data = dict()
            for key, value in args.items():
                if value != None:
                    data[key] = value

            result, message = signalManager.actionGetlistPackage.emit(data, jwt)
            if result:
                # json_dumps = getListPackagesSchema.dump(result.items)
                replace_key = '******'
                response = []
                for p, a in result.items:
                    t = p.to_dict()
                    if p.geo_location != "" and isinstance(p.geo_location, str):
                        t['geo_location'] = json.loads(p.geo_location)
                    if p.remarks != "" and isinstance(p.remarks, str):
                        t['remarks'] = json.loads(p.remarks)
                        t['remarks']['appDir'] = replace_key + t['remarks']['appDir'][len(replace_key):]
                    t['app_name'] = a.app_name
                    t['file_dir'] = os.path.dirname(p.file_path)
                    t['application'] = a.to_dict()
                    t['package_info'] = json.loads(p.package_info)
                    t['package_info']['epkfile'] = replace_key + t['package_info']['epkfile'][len(replace_key):]
                    response.append(t)
                return response_result(message, data=response, total=result.total, pageSize=args.pageSize)
            return response_result(message)
        except Exception as e:
            traceback.print_exc()
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)

class PackageResource(Resource):
    def __init__(self):
        # 特殊参数，即不是从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:
            jwt = get_jwt_identity()
            json_payload = request.json
            print("========>", uuid, json_payload)
            result, message = signalManager.actionGetPackage.emit(uuid, jwt)
            if result:
                json_dumps = getPackageSchema.dump(result)
                return response_result(message, data=json_dumps)
            return response_result(message)
        except Exception as e:
            traceback.print_exc()
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
