from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated

from utils.custom import CommonPagination, TreeAPIView
from ..permission import RbacPermission
from ..models import Menu
from ..serializers.menu_serializer import MenuSerializer


class MenuViewSet(ModelViewSet):
    """
    菜单管理：增删改查
    """

    perms_map = ({'get': 'menu_list'}, {'post': 'menu_create'}, {'put': 'menu_update'},
                 {'delete': 'menu_delete'})
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer
    pagination_class = None
    filter_backends = (SearchFilter, OrderingFilter)
    search_fields = ('name',)
    ordering_fields = ('sort',)
    permission_classes = (IsAuthenticated,RbacPermission)
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        if request.method == 'GET':
            pass
        else:
            for permission in self.get_permissions():
                if not permission.has_permission(request, self):
                    self.permission_denied(
                        request, message=getattr(permission, 'message', None)
                    )


class MenuTreeView(TreeAPIView):
    """
    菜单树
    """
    queryset = Menu.objects.all()
    pagination_class = None
    permission_classes = ()
