from datetime import datetime

from sqlalchemy.orm import Session

from app.api.users import schemas
from libs.functions import md5
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, hashed_password=md5(user.password), create_time=datetime.now())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
