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

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 marshmallow.exceptions import ValidationError
from application.signal_manager import signalManager
from models.login import  postLoginSchema, getListLoginSchema, getListLoginsSchema, getLoginSchema
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result

class LoginResourceList(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 = getListLoginSchema.load(json_payload)
            result, message = signalManager.actionGetlistLogin.emit(data)
            json_dumps = getListLoginSchema.dump(result)
            if result:
                json_dumps = getListLoginsSchema.dump(result.items)
                return response_result(message, data=json_dumps, count=result.total)
            return response_result(message)
        except ValidationError as e:
            return response_result(ResponseCode.HTTP_INVAILD_REQUEST, data=e.messages)
        except Exception as e:
            data = None
            if hasattr(e, 'args'):
                data = e.args
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR, data=data)

    def post(self):
        try:
            json_payload = request.json
            data = postLoginSchema.load(json_payload)
            # 更新data，插入ip信息，如果没有转发ip，那么则获取请求ip
            data.update({ "ip": request.headers.get('X-Forwarded-For', request.remote_addr), "user_agent": request.headers.get('User-Agent', "") })
            print("###############=======================>", data)
            logger.info(data)
            result, message = signalManager.actionPostLogin.emit(data)
            print(">>>>>>>>>>>", result)
            return response_result(message, data=result)
        except ValidationError as e:
            return response_result(ResponseCode.HTTP_INVAILD_REQUEST, data=e.messages)
        except Exception as e:
            traceback.print_exc()
            data = None
            if hasattr(e, 'args'):
                data = e.args
            current_app.logger.error(e)
            traceback.print_exc()
            return response_result(ResponseCode.HTTP_SERVER_ERROR, data=data)


class LoginResource(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 = getLoginSchema.load(json_payload)
            result, message = signalManager.actionGetLogin.emit(uuid, data)
            if result:
                json_dumps = getLoginSchema.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)
