import json
from functools import wraps

from django.http import HttpResponse
from alpha_types.venus.error import ERROR as CODES
from helios.rpc import RPCFaultException

from libs.utils import DictWrapperUseDot
from engine.logger import auth_logger
from engine.rpc import get_current_rpc_invoker


def get_user_by_request(request):
    """获取用户信息"""

    try:
        user_info = request.rpc["venus/account/user/self_user_detail"]().unwrap()
    except:
        return None

    if not user_info["logined"]:
        return None

    info = {
        "id": user_info["user_id"],
        "user_id": user_info["user_id"],
        "nick_name": user_info["nick_name"],
        "profile_pic": user_info["profile_pic"],
        "city_id": user_info["city_id"],
        "gender": user_info["gender"],
        "register_time": user_info["register_time"],
    }

    return DictWrapperUseDot(info)


def get_user_by_ids(user_ids):
    """获取用户信息"""

    try:
        rpc = get_current_rpc_invoker()
        users_info = rpc["venus/account/user/userinfo_list"](user_ids=user_ids).unwrap()
    except:
        return None

    return users_info


def auth(request):
    user_info = get_user_by_request(request)
    if not user_info:
        return False

    request.user = user_info

    return True


def login_required(view_func):
    """登录校验"""

    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):

        if auth(request):
            return view_func(request, *args, **kwargs)

        request_data = {'request': {key: value for key, value in request.REQUEST.items()}}
        auth_logger.error(json.dumps(request_data))

        result = {
            'error': 1,
            'message': CODES.getDesc(CODES.LOGIN_REQUIRED),
            'error_code': CODES.LOGIN_REQUIRED,
        }

        return HttpResponse(status=403, content=json.dumps(result))

    return _wrapped_view

