from typing import Optional, Any

from graphql import GraphQLResolveInfo

from core.get_value import get_value
from data.schemas.administration.user import User
from data.schemas.permission.permission import Permission
from service.permission.permissions_enum import Permissions


class QueryContext:

    def __init__(
        self,
        data: Any,
        user: Optional[User],
        user_permissions: Optional[list[Permissions]],
        *args,
        **kwargs
    ):

        self._data = data
        self._user = user
        if user_permissions is None:
            user_permissions = []
        self._user_permissions: list[str] = [x.value for x in user_permissions]

        self._resolve_info = None
        for arg in args:
            if isinstance(arg, GraphQLResolveInfo):
                self._resolve_info = arg
                continue

        self._filter = kwargs.get("filter", {})
        self._sort = kwargs.get("sort", {})
        self._skip = get_value(kwargs, "skip", int)
        self._take = get_value(kwargs, "take", int)

    @property
    def data(self):
        return self._data

    @property
    def user(self) -> User:
        return self._user

    @property
    def resolve_info(self) -> Optional[GraphQLResolveInfo]:
        return self._resolve_info

    @property
    def filter(self) -> dict:
        return self._filter

    @property
    def sort(self) -> dict:
        return self._sort

    @property
    def skip(self) -> Optional[int]:
        return self._skip

    @property
    def take(self) -> Optional[int]:
        return self._take

    def has_permission(self, permission: Permissions) -> bool:
        return permission.value in self._user_permissions
