from datetime import datetime
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):
    user = db.query(models.User).filter(models.User.id == user_id).first()
    user_dict = {
        "authority": user.authority,
        "config_key": user.config_key,
        "create_time": str(user.create_time),
        "description": user.description,
        "google_key": user.google_key,
        "hashed_password": user.hashed_password,
        "id": user.id,
        "remaining_sum": user.remaining_sum,
        "unique": user.unique,
        "update_time": str(user.update_time),
        "username": user.username,
        "uuid": user.uuid,
    }
    return user_dict


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"),
                          create_time=datetime.now())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
