#!/usr/bin/env python
# -*- coding: utf_8 -*-

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
{%- set pipe = joiner(",") %}
{%- if "restful" not in config.get("view") or config.get("view").get("restful", None) %}
from models.{{ config['name'] }} import {% for k, v in config["view"].items() -%}
{{ pipe() }} {{ k }}{{ config['name'] | capitalize }}Schema{% if k == "getList" %}{{ pipe() }} {{ k }}{{ config['name'] | capitalize }}sSchema{% endif %}
{%- endif %}
{%- endfor %}
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
{#
    判断是否是标准的RESTful请求方式，默认为RESTful请求方式
#}
{% if config["view"].get("restful", None) == None %}
class {{ config['name'] | capitalize }}ResourceList(Resource):
    def __init__(self):
        pass
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser = RequestParser()

{%- if config["view"]["getList"] %}
{% if config["view"]["getList"]["auth"] %}
    @jwt_required(locations=["headers"])
{%- endif %}
    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 = getList{{ config['name'] | capitalize }}Schema.load(json_payload)
            result, message = signalManager.actionGetlist{{ config["name"] | capitalize }}.emit(data)
            json_dumps = getList{{ config['name'] | capitalize }}Schema.dump(result)
            if result:
                json_dumps = getList{{ config['name'] | capitalize }}sSchema.dump(result.items)
                logger.warn(json_dumps)
                return response_result(message, data=json_dumps, count=result.total)
            return response_result(message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{%- endif %}

{%- if config["view"]["post"] %}
{% if config["view"]["post"]["auth"] %}
    @jwt_required(locations=["headers"])
{%- endif %}
    def post(self):
        try:
            json_payload = request.json
            data = post{{ config['name'] | capitalize }}Schema.load(json_payload)
            result, message = signalManager.actionPost{{ config["name"] | capitalize }}.emit(data)
            logger.info(result)
            logger.warn(message)
            return response_result(message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{% endif %}

class {{ config['name'] | capitalize }}Resource(Resource):
    def __init__(self):
        pass
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        # self.parser = RequestParser()

{%- if config["view"]["get"] %}
{% if config["view"]["get"]["auth"] %}
    @jwt_required(locations=["headers"])
{%- endif %}
    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 = get{{ config['name'] | capitalize }}Schema.load(json_payload)
            result, message = signalManager.actionGet{{ config["name"] | capitalize }}.emit(uuid, data)
            if result:
                json_dumps = get{{ config['name'] | capitalize }}Schema.dump(result)
                return response_result(message, data=json_dumps)
            return response_result(message)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{% endif %}

{%- if config["view"]["put"] %}
{% if config["view"]["put"]["auth"] %}
    @jwt_required(locations=["headers"])
{%- endif %}
    def put(self, uuid):
        try:
            json_payload = request.json
            print("========>", uuid, json_payload)
            data = put{{ config['name'] | capitalize }}Schema.load(json_payload)
            result, message = signalManager.actionPut{{ config["name"] | capitalize }}.emit(uuid, data)
            logger.info(result)
            logger.info(message)
            return response_result(message, data=result)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{% endif %}

{%- if config["view"]["delete"] %}
{% if config["view"]["delete"]["auth"] %}
    @jwt_required(locations=["headers"])
{%- endif %}
    def delete(self, uuid):
        try:
            json_payload = request.json
            print("========>", uuid, json_payload)
            # data = delete{{ config['name'] | capitalize }}Schema.load(json_payload)
            result, message = signalManager.actionDelete{{ config["name"] | capitalize }}.emit(uuid)
            return response_result(message, data=result)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{% endif %}
{%- elif "restful" in config.get("view") and config.get("view").get("restful") == False %}
{%- for route in config.get("view").get("routes", []) %}
class {{ route.get("name") | capitalize }}(Resource):
    def __init__(self):
        self.parser = RequestParser()
        
    def {{ route.get("method") }}(self):
    {%- for r in route.get("params", []) %}
        self.parser.add_argument("{{ r.get("name") }}", type={{ r.get("dataType") | getDataType }}, location="{{ r.get('location') }}", {% if "default" in r %}default={{ r.get("default") | getVariableString }}{% endif %}, required={% if r.get("required") %}True{% else %}False{% endif %})
    {%- endfor %}
        args = self.parser.parse_args()

        try:
            print("========>", args)
            result, message = signalManager.action{{ route.get("name") | capitalize }}.emit(args)
            return response_result(message, data=result)
        except Exception as e:
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)
{% endfor %}
{% endif %}