from api_graphql.abc.db_history_model_query_abc import DbHistoryModelQueryABC
from api_graphql.field.resolver_field_builder import ResolverFieldBuilder
from api_graphql.require_any_resolvers import by_group_assignment_resolver
from data.schemas.public.group import Group
from data.schemas.public.group_dao import groupDao
from data.schemas.public.group_role_assignment_dao import groupRoleAssignmentDao
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 GroupHistoryQuery(DbHistoryModelQueryABC):
    def __init__(self):
        DbHistoryModelQueryABC.__init__(self, "Group")

        self.set_field("name", lambda x, *_: x.name)
        self.set_field("userSpace", lambda x, *_: x.user_space)
        self.field(
            ResolverFieldBuilder("shortUrls")
            .with_resolver(self._get_urls)
            .with_require_any(
                [
                    Permissions.groups,
                ],
                [by_group_assignment_resolver],
            )
        )
        self.set_field(
            "roles",
            lambda x, *_: self._resolve_foreign_history(
                x.updated,
                x.id,
                groupRoleAssignmentDao,
                groupDao,
                lambda y: y.role_id,
                obj_key="groupid",
            ),
        )

    @staticmethod
    async def _get_urls(group: Group, *_):
        return await shortUrlDao.find_by(
            [
                {ShortUrl.group_id: group.id},
                {ShortUrl.deleted: False},
                {"updated": {"lessOrEqual": group.updated}},
            ]
        )
