from datetime import datetime

import pyotp
from sqlalchemy.orm import Session

from app.api.users import schemas
from libs.functions import md5, uuid
from models import users as models


def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_user_by_name(db: Session, username: str):
    return db.query(models.User).filter(models.User.username == username).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
    db_user = models.User(username=user.username, description=user.description, unique=user.unique,
                          config_key=user.config_key, uuid=uuid(), hashed_password=md5("123456"),
                          google_key=pyotp.random_base32(64), create_time=datetime.now())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
