from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.domain_create_input import DomainCreateInput
from api_graphql.input.domain_update_input import DomainUpdateInput
from api_graphql.input.group_create_input import GroupCreateInput
from api_graphql.input.group_update_input import GroupUpdateInput
from core.logger import APILogger
from data.schemas.public.domain_dao import domainDao
from data.schemas.public.group import Group
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class DomainMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "Domain")

        self.mutation(
            "create",
            self.resolve_create,
            DomainCreateInput,
            require_any_permission=[Permissions.domains_create],
        )
        self.mutation(
            "update",
            self.resolve_update,
            DomainUpdateInput,
            require_any_permission=[Permissions.domains_update],
        )
        self.mutation(
            "delete",
            self.resolve_delete,
            require_any_permission=[Permissions.domains_delete],
        )
        self.mutation(
            "restore",
            self.resolve_restore,
            require_any_permission=[Permissions.domains_delete],
        )

    @staticmethod
    async def resolve_create(obj: GroupCreateInput, *_):
        logger.debug(f"create domain: {obj.__dict__}")

        domain = Group(
            0,
            obj.name,
        )
        nid = await domainDao.create(domain)
        return await domainDao.get_by_id(nid)

    @staticmethod
    async def resolve_update(obj: GroupUpdateInput, *_):
        logger.debug(f"update domain: {input}")

        if obj.name is not None:
            domain = await domainDao.get_by_id(obj.id)
            domain.name = obj.name
            await domainDao.update(domain)

        return await domainDao.get_by_id(obj.id)

    @staticmethod
    async def resolve_delete(*_, id: str):
        logger.debug(f"delete domain: {id}")
        domain = await domainDao.get_by_id(id)
        await domainDao.delete(domain)
        return True

    @staticmethod
    async def resolve_restore(*_, id: str):
        logger.debug(f"restore domain: {id}")
        domain = await domainDao.get_by_id(id)
        await domainDao.restore(domain)
        return True
