from typing import List
from fastapi import Depends, APIRouter
from datetime import timedelta
from sqlalchemy.orm import Session
from app import get_db
from app.api.users import crud, schemas
from app.api.users.login_verification import authenticate_user, create_access_token, get_user
from app.api.users.schemas import UserLoginForm, GoogleCode, GoogleLogin
from libs.google_code import get_qrcode, google_verify_result
from libs.img_code import imageCode
from libs.result_format import HttpResultResponse, HttpMessage

router = APIRouter()


@router.get("/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return users


@router.get("/imgCode")
def imgCode():
    return HttpResultResponse(data=imageCode().getImgCode())


@router.post("/login")
async def login(form_data: UserLoginForm, db: Session = Depends(get_db)):
    user, msg = authenticate_user(db=db, form_data=form_data)
    if not user:
        return HttpResultResponse(code=500, msg=msg, data={})
    # 定义tokens过期时间
    access_token_expires = timedelta(hours=12)
    access_token = create_access_token(data=form_data.dict(), expires_delta=access_token_expires)
    return HttpResultResponse(msg=HttpMessage.HFDU, data={"access_token": access_token, "token_type": "bearer"})


@router.post("/goodleCode")
async def goodleCode(data: GoogleCode, db: Session = Depends(get_db)):
    user_data = get_user(db, data.username)
    return get_qrcode(username=user_data.username, gtoken=user_data.google_key)


@router.post("/googleLogin")
async def googleLogin(data: GoogleLogin, db: Session = Depends(get_db)):
    user_data = get_user(db, data.username)
    verify = google_verify_result(secret_key=user_data.google_key, google_code=data.google_code)
    if verify:
        return HttpResultResponse(msg=HttpMessage.HFDU)
    else:
        return HttpResultResponse(msg="登录失败,谷歌动态码错误")


@router.post("/create")
def create_user(data: schemas.UserCreate, db: Session = Depends(get_db)):
    """添加用户"""
    db_user = crud.get_user_by_name(db, username=data.username)
    if db_user:
        return HttpResultResponse(code=400, msg=HttpMessage.USER_EXIST)
    res = crud.create_user(db=db, user=data)
    return HttpResultResponse(data=res.id)
