from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from vod.models import Course, Video
from rest_framework.response import Response
from vod.serializers import CourseSerializer, VideoSerializer
from vod.vodclient import getSignature
from utils.custom import CommonPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter
from django.db.models import Q
# Create your views here.

class CourseViewSet(ModelViewSet):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    ordering = ['id']
    perms_map = [
        {'get': '*'}, {'post': 'vod'},
        {'put': 'vod'}, {'delete': 'vod'}]
    # def get_queryset(self):
    #     queryset = self.queryset
    #     if hasattr(self.get_serializer_class(), 'setup_eager_loading'):
    #         queryset = self.get_serializer_class().setup_eager_loading(queryset)
    #     if self.request.user.is_superuser:
    #         return queryset
    #     roles = self.request.user.roles.values_list('name', flat=True)
    #     if '普通管理' in roles:
    #         queryset = queryset.filter(Q(create_admin = self.request.user)|Q(create_admin=self.request.user))
    #     else:
    #         return queryset.none()
    #     return queryset

    def perform_create(self, serializer):
        serializer.save(create_admin=self.request.user)

class VideoViewSet(ModelViewSet):
    queryset = Video.objects.all()
    filterset_fields = ['course']
    pagination_class = CommonPagination
    serializer_class = VideoSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    ordering = ['-id']
    perms_map = [
        {'get': '*'}, {'post': 'vod'},
        {'put': 'vod'}, {'delete': 'vod'}]
    # def get_queryset(self):
    #     queryset = self.queryset
    #     if hasattr(self.get_serializer_class(), 'setup_eager_loading'):
    #         queryset = self.get_serializer_class().setup_eager_loading(queryset)  # 性能优化
    #     if self.request.user.is_superuser:
    #         return queryset      
    #     roles = self.request.user.roles.values_list('name', flat=True)
    #     if '普通管理' in roles:
    #         queryset = queryset.filter(course__create_admin = self.request.user)
    #     else:
    #         return queryset.none()
    #     return queryset


class SignatureAPIView(APIView):
    perms_map = [{'get': 'vod'}]
    def get(self, request, format=None):
        """
        获取上传签名
        """
        signature = getSignature(procedure=request.query_params.get('procedure', None))
        return Response({'signature':signature})