# _*_ coding: utf-8 _*_
# @Time     :   2020/9/29 16:33
# @Author       vanwhebin
from __future__ import absolute_import, unicode_literals

import os
import time

from rest_framework.generics import CreateAPIView
from usercenter.serializers import MediaSerializer
from usercenter.models import Media
from wxProject.settings import MEDIA_ROOT, UPLOAD_MEDIA_CHOICES
from utils.util import uuid, get_md5_hash, response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework import status


def upload_media(uploaded_file, uploaded_file_ext, user):
	""" 处理上传新建媒体记录 """
	hash_file_name = uuid() + uploaded_file_ext
	time_tag = time.strftime('%Y-%m-%d')
	file_path = time_tag + os.sep + hash_file_name
	dir_path = os.path.join(MEDIA_ROOT, time_tag)

	if not os.path.exists(dir_path):
		os.makedirs(dir_path)
	with open(os.path.join(dir_path, hash_file_name), 'wb') as f:
		f.write(uploaded_file.read())

	file_hash = get_md5_hash(os.path.join(dir_path, hash_file_name))
	file_size = int(uploaded_file.size / 1024)
	file = Media.objects.filter(hash=file_hash, size=file_size).first()
	if not file:
		file = Media.objects.create(
			file=uploaded_file,
			file_name=uploaded_file.name,
			hash=file_hash,
			user=user,
			size=file_size,
			extension=uploaded_file_ext
		)
	os.remove(os.path.join(MEDIA_ROOT, file_path))
	return file


class UploadMedia(CreateAPIView):
	serializer_class = MediaSerializer
	permission_classes = (IsAuthenticated, )

	def post(self, request, *args, **kwargs):
		super(UploadMedia, self).__init__()
		uploaded_file = request.FILES.get('file')
		uploaded_file.name = uploaded_file.name.strip('"')

		if not uploaded_file:
			return response(msg=u"文件上传失败", status_code=status.HTTP_400_BAD_REQUEST)
		ext_pos = uploaded_file.name.rfind('.')
		uploaded_file_ext = uploaded_file.name[ext_pos:]
		if not self.allowed_extension(uploaded_file_ext):
			return response(msg="非法文件类型", status_code=status.HTTP_400_BAD_REQUEST)
		file = upload_media(uploaded_file, uploaded_file_ext, request.user)
		return response(MediaSerializer(file, context={'request': request}).data)

	@staticmethod
	def allowed_extension(ext, allowed_ext=None):
		choices = allowed_ext if allowed_ext else UPLOAD_MEDIA_CHOICES
		for allowed_ext in choices:
			if ext == allowed_ext[0]:
				return True
		return False

	def allowed_file_size(self, size):
		pass