import datetime
from sqlalchemy.orm import Session
from fastapi import Depends, APIRouter, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from pydantic import BaseModel
from typing import Union

from app import get_db
from app.api.users.login_verification import SECRET_KEY, ALGORITHM, get_user

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


def auth_token(token: str = Depends(oauth2_scheme)):
    try:
        # 解密tokens
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        # 从tokens的载荷payload中获取用户名
        username: str = payload.get('username')
        # 如果没有获取到,抛出异常
        if username is None:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='用户不存在')
        now_time = int(datetime.datetime.now().timestamp())
        if payload.get("exp") <= now_time:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='token过期')
        return token
    except JWTError as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f'{e}')


def get_current_user(db: Session, token: str = Depends(oauth2_scheme)):
    '''获取当前用户信息,实际上是一个解密token的过程
    :param token: 携带的token
    :return:
    '''
    try:
        # 解密tokens
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        # 从tokens的载荷payload中获取用户名
        username: str = payload.get('username')
        user_data = get_user(db=db, username=username)
        json_data = {
            "username": user_data.username
        }
        return json_data
    except JWTError as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f'{e}')
