from datetime import timedelta
from time import timezone
from apps.system.models import Dict
from rest_framework.mixins import ListModelMixin
from apps.vod.serializers import VRecordSerializer, VRecordUpdateSerializer, VideoListDetailSerializer, VideoSerializer, VideoUpdateSerializer
from apps.vod.models import Video, ViewRecord
from django.shortcuts import render
from .vodclient import getAllClass, getPlayCode, searchMedia, getSignature
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from utils.pagination import PageOrNot
from apps.system.mixins import CreateUpdateModelAMixin
from rest_framework.decorators import action, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.status import HTTP_400_BAD_REQUEST
from django.utils import timezone
from rest_framework.exceptions import ParseError
from utils.queryset import get_child_queryset2
# Create your views here.

class ClassView(APIView):

    perms_map={'get':'*'}
    def get(self, request, format=None):
        """
        查询分类
        """
        return getAllClass()

class VideoView(APIView):

    perms_map={'get':'video_view'}
    def get(self, request, format=None):
        """
        查询视频
        """
        params={'Filters':['basicInfo', 'metaData']}
        params['Offset'] = request.query_params.get('Offset', 0)
        params['Limit'] = request.query_params.get('Limit', 20)
        params['Names'] = request.query_params.getlist('name') if request.query_params.get('name') else []
        params['ClassIds']= request.query_params.getlist('classid') if request.query_params.get('classid') else []
        return searchMedia(params)

class VideoViewSet(PageOrNot, CreateUpdateModelAMixin, ModelViewSet):
    perms_map={'get':'video_view', 'post':'video_create', 'put':'video_update', 'delete':'video_delete'}
    queryset = Video.objects.all()
    search_fields = ['name', 'category__name', 'description']
    # filterset_fields = ['category']
    serializer_class = VideoSerializer
    ordering_fields = ['create_time', 'sort_str', 'views', 'viewsp']
    ordering = ['sort_str', '-create_time']

    def get_serializer_class(self):
        if self.action in ['list', 'retrieve']:
            return VideoListDetailSerializer
        elif self.action in ['update']:
            return VideoUpdateSerializer
        return super().get_serializer_class()

    def get_queryset(self):
        queryset = super().get_queryset()
        category = self.request.query_params.get('category', None)
        if category:
            categorys = get_child_queryset2(Dict.objects.get(pk=category))
            queryset = queryset.filter(category__in=categorys)
        return queryset
    
    @action(methods=['get'], detail=False, perms_map={'get':'video_view'})
    def myview(self, request, *args, **kwargs):
        """
        个人观看记录
        """
        queryset = ViewRecord.objects.filter(user=request.user).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = VRecordSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = VRecordSerializer(queryset, many=True)
        return Response(serializer.data)



class VRecordViewSet(ListModelMixin, GenericViewSet):
    perms_map = {'get':'viewrecord_view'}
    queryset = ViewRecord.objects.all()
    search_fields = ['user__name', 'video__name']
    serializer_class = VRecordSerializer
    ordering = ['-update_time']
    

    
class MyViewRecordAPIView(APIView):

    permission_classes = [IsAuthenticated]
    def get(self, request, id , format=None):
        """
        该视频的本人观看信息
        """
        try:
            video = Video.objects.get(pk=id)
        except:
            return Response('视频不存在', status=HTTP_400_BAD_REQUEST)
        record, _ = ViewRecord.objects.get_or_create(video=video, user=request.user, defaults={'video':video, 'user':request.user})
        serializer = VRecordSerializer(instance=record)
        return Response(serializer.data)

    def put(self, request, id, format=None):
        """
        更新该视频本人的观看信息
        params: {current:int}
        """
        try:
            video = Video.objects.get(pk=id)
        except:
            return Response('视频不存在', status=HTTP_400_BAD_REQUEST)
        
        record = ViewRecord.objects.filter(video=video, user=request.user).first()
        fcreated = True
        if record:
            fcreated = False
        else:
            record = ViewRecord.objects.create(video=video, user=request.user)

        if fcreated:
            video.viewsp = video.viewsp + 1
            video.views = video.views + 1
            record.views = 1
            video.save()
        if request.data.get('current', None):
            record.current = request.data.get('current')
        if timezone.now() > record.update_time + timedelta(hours=6):
            record.views = record.views + 1
            video.views = video.views + 1
            video.save()
        record.save()
        return Response()

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


class PlayCodeAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, fileId):
        """获取播放签名
        """
        from .vodclient import appId
        try:
            playcode = getPlayCode(fileId)
        except:
            raise ParseError('获取签名失败')
        return Response({'psign':playcode, 'appId': appId})
