from datetime import datetime
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from app.api.role import schemas
from libs.functions import wrapper_out
from models import roles as models


def get_role_by_name(db: Session, role_name: str):
    return db.query(models.Role).filter(models.Role.role_name == role_name).first()


def get_id_to_authority(db: Session, role_id: int):
    return db.query(models.Role).filter(models.Role.id == role_id).first()


@wrapper_out()
def get_roles(db: Session, param):
    result_list = []
    name = param.role_name if param.role_name else ""
    if name:
        query_res = db.query(models.Role).filter(models.Role.role_name.like(f'%{name}%')).\
            offset((int(param.page) - 1) * param.size).limit(param.page * param.size).all()
    else:
        query_res = db.query(models.Role).offset((int(param.page) - 1) * param.size).limit(param.page * param.size).all()
    if not query_res:
        return []
    for i in query_res:
        serializer_info = i.to_dict(only=('id', 'role_name', 'authority', 'remark', 'create_time'))
        if i.authority:
            auth_list = serializer_info.get('authority').split(',')
            serializer_info['authority'] = [int(i) for i in auth_list]
        else:
            serializer_info['authority'] = []
        result_list.append(serializer_info)
    return result_list


def create_role(db: Session, user: schemas.RoleCreate):
    try:
        db_user = models.Role(role_name=user.role_name, authority=",".join(map(str, user.authority)),
                              remark=user.remark, create_time=datetime.now())
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
    except Exception as e:
        print(e)
        return {}
    return db_user


def update_role(db: Session, role_info):

    if role_info.role_name:
        db.query(models.Role).filter(models.Role.id == role_info.id).update(
            {models.Role.role_name: role_info.role_name})
    if role_info.remark:
        db.query(models.Role).filter(models.Role.id == role_info.id).update(
            {models.Role.remark: role_info.remark})
    if role_info.authority:
        db.query(models.Role).filter(models.Role.id == role_info.id).update(
            {models.Role.authority: ','.join(map(str, role_info.authority))})
    db.commit()


def delete_role(db: Session, role_id: int):
    from models import users as model
    user_info = db.query(model.User).filter(model.User.role_id == role_id).first()
    if user_info:
        return False
    db.query(models.Role).filter(models.Role.id == role_id).delete()
    db.commit()
    return True
