import datetime
from uuid import uuid4
import logging

from django.conf import settings

from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import GenericAPIView
from rest_framework.parsers import FileUploadParser, MultiPartParser
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.response import Response
from rest_framework import status

from common.third_party_api.qucloud.clients import cos_client
from common.utils.exceptions import ServiceHandleException
from common.utils.views import BaseApiView
from common.utils.service_code import DATA_ERROR, THIRD_PARTY_API_ERROR
from .serializers import FileUploadSerializers
from .services import watermark_with_text

Logger = logging.getLogger('')
file_path = settings.UPLOAD_FILE_PATH


class FileUploadView(GenericAPIView):
    serializer_class = FileUploadSerializers
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JSONWebTokenAuthentication, )
    parser_classes = (
        MultiPartParser,
        FileUploadParser,
    )
    renderer_classes = (JSONRenderer, BrowsableAPIRenderer)

    def post(self, request, *args, **kwargs):
        file_id = str(uuid4())

        if not request.FILES or not request.FILES.get('file'):
            return Response({"msg": "请指定需要上传的文件"},
                            status=status.HTTP_400_BAD_REQUEST)
        file = request.FILES.get('file')
        serializer = FileUploadSerializers(data=request.data)
        serializer.is_valid(raise_exception=True)
        bucket = settings.CLOUD_COS.UPLOAD_BUCKET
        key = file_id + "." + file.name.split(".")[-1]
        suffix = file.name.split(".")[-1]
        if suffix.lower() in ["png", "jpg", "jpeg"]:
            try:
                file = watermark_with_text(file, str(datetime.datetime.now()),
                                           key)
                bucket = settings.CLOUD_COS.IMAGE_BUCKET
            except Exception as e:
                raise ServiceHandleException(msg_show="水印添加失败，请重新上传",
                                             msg=e,
                                             code=DATA_ERROR)
        response = cos_client.put_object(Bucket=bucket,
                                         Body=file,
                                         Key=key,
                                         EnableMD5=False)
        url = cos_client._conf.uri(bucket=bucket, path=key)
        if response.get("ETag"):
            return Response({"url": url}, status=status.HTTP_200_OK)
        else:
            raise ServiceHandleException(msg_show="上传失败",
                                         msg="upload error",
                                         code=THIRD_PARTY_API_ERROR)


class UploadDView(BaseApiView):
    def delete(self, request, *args, **kwargs):
        uri = request.data.get("url")
        try:
            cos_client.delete_object_by_url(uri)
        except Exception:
            pass
        return Response(None, status=status.HTTP_200_OK)
