from config import AnonymousIn_schema, RoomIn_schema, User_schema from database.auth.models import UserModel from .models import AnonymousMember, Room, RoomOwner, Waiter from database.exercices.crud import generate_unique_code async def create_room_with_user_db(room: RoomIn_schema, user: User_schema): code = await generate_unique_code(Room) room_obj = await Room.create(**room.dict(exclude_unset=True), id_code=code) user = await UserModel.get(id=user.id) await room_obj.users.add(user) await RoomOwner.create(room_id=room_obj.id, user_id=user.id) return room_obj async def create_room_anonymous_db(room: RoomIn_schema, anonymous: AnonymousIn_schema): code = await generate_unique_code(Room) room_obj = await Room.create(**room.dict(exclude_unset=True), id_code=code) anonymous_code = await generate_unique_code(AnonymousMember) anonymous = await AnonymousMember.create(**anonymous.dict(exclude_unset=True), id_code=anonymous_code, room_id=room_obj.id) await RoomOwner.create(room_id=room_obj.id, anonymous_id=anonymous.id) return room_obj async def get_room_db(room_id:str): room = await Room.get_or_none(id_code=room_id) return room async def check_user_in_room(room: Room, user: UserModel): return await room.users.filter(id=user.id).count() != 0 async def get_member_by_code(room: Room, code: str): anonymous = await room.anonymousmembers filtered_anonymous = [ m for m in anonymous if m.id_code == code] if len(filtered_anonymous) == 0: return None return filtered_anonymous[0] async def check_user_owner(room: Room, user: UserModel): room_owner = await room.room_owner user_owner = await room_owner.user if user_owner == None: return False return user_owner.id == user.id async def check_anonymous_owner(room: Room, anonymous: AnonymousMember): room_owner = await room.room_owner anonymous_owner = await room_owner.anonymous if anonymous_owner == None: return False return anonymous_owner.id_code == anonymous.id_code async def create_waiter_by_user(room: Room, user: UserModel ): code = await generate_unique_code(Waiter) return await Waiter.create(room_id=room.id, user_id=user.id, name=user.username, id_code=code) async def create_waiter_anonymous(room: Room, name: str): code = await generate_unique_code(Waiter) return await Waiter.create(name=name, id_code=code, room_id=room.id) async def connect_room(room: Room, code): online = room.online await room.update_from_dict({'online': [*online, code]}).save(update_fields=['online']) return async def disconnect_room(room: Room, code): online = room.online await room.update_from_dict({'online': [o for o in online if o!=code]}).save(update_fields=['online']) return async def validate_name_in_room(room: Room, name): anonymous = await room.anonymousmembers if len([a for a in anonymous if a == name]) != 0: return "Pseudo déjà utilisé" if len(name) < 3: return "Pseudo trop court" if len(name) > 30: return "Pseudo trop long" return True