import ujson
from sanic import Blueprint, response
from sanic.views import HTTPMethodView

from pot_libs.aiohttp_util.aiohttp_utils import AioHttpUtils
from pot_libs.settings import SETTING

refresh_blueprint = Blueprint("refresh_token", url_prefix="/unify-api")


class RefreshView(HTTPMethodView):
    """获取refresh_token"""

    async def post(self, request, *args, **kwargs):
        refresh_token = request.json.get("refresh_token")
        client_name = request.json.get("client_name")
        token = request.token
        if not client_name:
            return response.json({"code": 40001, "data": None,
                                  "message": "miss param client_name"},
                                 status=200)
        resp, status_code = await AioHttpUtils().post(
            SETTING.refresh_token_url,
            {
                "refresh_token": refresh_token,
                "client_name": client_name,
                "db": SETTING.mysql_db
            },
            timeout=50,
            headers={"Authorization": f"Bearer {token}"}
        )
        return response.json(ujson.loads(resp), status=status_code)


refresh_blueprint.add_route(RefreshView.as_view(), "/refresh_token")