from api_graphql.abc.db_model_query_abc import DbModelQueryABC
from api_graphql.field.resolver_field_builder import ResolverFieldBuilder
from api_graphql.require_any_resolvers import group_by_assignment_resolver
from data.schemas.public.group import Group
from data.schemas.public.group_dao import groupDao
from data.schemas.public.short_url import ShortUrl
from data.schemas.public.short_url_dao import shortUrlDao
from service.permission.permissions_enum import Permissions


class GroupQuery(DbModelQueryABC):
    def __init__(self):
        DbModelQueryABC.__init__(self, "Group")

        self.set_field("name", lambda x, *_: x.name)
        self.field(
            ResolverFieldBuilder("shortUrls")
            .with_resolver(self._get_urls)
            .with_require_any([
                Permissions.groups,
            ], [group_by_assignment_resolver])
        )
        self.set_field("roles", self._get_roles)

    @staticmethod
    async def _get_urls(group: Group, *_):
        return await shortUrlDao.find_by({ShortUrl.group_id: group.id})

    @staticmethod
    async def _get_roles(group: Group, *_):
        return await groupDao.get_roles(group.id)
