# -*- coding: utf-8 -*-
import json


from cacheout import LFUCache
from furl import furl
from torndsession.sessionhandler import SessionBaseHandler
from auth.subassembly import AuthenticationController,Sign
from log import log

logger = log(__name__)

cache = LFUCache()
class BaseHandler(SessionBaseHandler):
    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)

    def SetDownLoadHeadler(self, fileName):
        fileName = fileName.encode("gb2312").decode('latin-1')  # 支持中文文件名
        self.set_header('Content-Type', 'application/octet-stream charset=utf-8')
        self.set_header('Content-Disposition',
                        f"attachment; filename= {fileName}")

    def write_resp200(self, response, err_code=0, _err=''):
        self.set_header('Content-type', 'application/json')
        _response = {
            "err_code": err_code,
            "data": response,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp400(self, _err, response="", err_code=400):
        self.set_header('Content-type', 'application/json')
        _response = {
            "data": response,
            "err_code": err_code,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp500(self, response, err_code=500, _err=''):
        self.set_header('Content-type', 'application/json')
        _response = {
            "err_code": err_code,
            "data": response,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def json(self):
        return json.loads(self.request.body)

    def get_current_user(self):
        logger.info(f"*********headers:{self.request.headers}**********")
        dev_type = self.request.headers.get("Dev-Type")
        sign = ""
        auth = ""
        if not dev_type:
            logger.info("因无法获取devType鉴权失败")
            return
        if dev_type in ["HandTerminal", "Terminal", "GasTerminal"]:
            '''如果是终端类设备则校验该类型设备的AppKey'''
            #----------------公共请求鉴权---------------------------
        logger.info(f"*********headers:{self.request.headers}**********")
        sign = Sign()
        if self.request.method in ['GET', 'DELETE']:
            f = furl(self.request.uri)
            param = f.args
        elif self.request.method in ['POST', 'PUT']:
            param = self.json()
        sign.param = param
        auth = AuthenticationController()
        try:
            auth.devType = self.request.headers.get("Dev-Type")
            auth.reqSign = self.request.headers.get("Authorization")
            auth.sign = sign
            auth.session = self.session
            auth.token = self.request.cookies.get("token")
            auth.auth()
        except Exception as e:
            logger.error(f"通用鉴权时异常:{e}")
            return
        logger.info(f"鉴权结果:{auth.errMsg}")
        res = "ok" if auth.isPass else None
        return res