from app.models import KnowledgeModel, GroupModel, CanvasModel
from app.models.user_model import UserModel
from Log import logger


async def get_canvas_list(db, role, user_id):
    if role == "admin":
        canvas_list = db.query(CanvasModel).all()
    else:
        user = db.query(UserModel).filter(UserModel.id == user_id).first()

        group_list = [i.id for i in user.groups]

        canvas_list = db.query(CanvasModel).filter(CanvasModel.user_id == user_id).all()
        kld_set = set([i.id for i in canvas_list])
        for group in db.query(GroupModel).filter(GroupModel.id.in_(group_list)).all():
            for k in group.agents:
                if k.id not in kld_set:
                    canvas_list.append(k)
                    kld_set.add(k.id)

    return {"rows": [kld.to_json() for kld in canvas_list]}