#!/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 application.signal_manager import signalManager
from models.device import  postDeviceSchema, deleteDeviceSchema, getListDeviceSchema, getListDevicesSchema, getDeviceSchema, putDeviceSchema
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result

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

    @jwt_required(locations=["headers"])
    def get(self):
        # 特殊参数，即不是从json获取参数的接口，可以将这个注释打开
        self.parser.add_argument("name", type=str, location="args", required=False)
        self.parser.add_argument("imei", type=str, location="args", 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
            # json_payload = request.json
            # logger.warn(json_payload)
            # data = getListDeviceSchema.load(json_payload)
            logger.info(data)
            result, message = signalManager.actionGetlistDevice.emit(data, jwt)
            json_dumps = getListDeviceSchema.dump(result)
            if result:
                json_dumps = getListDevicesSchema.dump(result.items)
                return response_result(message, data=json_dumps, total=result.total, pageSize=args.pageSize)
            return response_result(message)
        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()
            json_payload = request.json
            data = postDeviceSchema.load(json_payload)
            result, message = signalManager.actionPostDevice.emit(data, jwt)
            logger.info(result)
            logger.warn(message)
            return response_result(message)
        except Exception as e:
            traceback.print_exc()
            current_app.logger.error(e)
            return response_result(ResponseCode.HTTP_SERVER_ERROR)


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


    @jwt_required(locations=["headers"])
    def put(self, uuid):
        try:
            json_payload = request.json
            print("========>", uuid, json_payload)
            data = putDeviceSchema.load(json_payload)
            result, message = signalManager.actionPutDevice.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)


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