import random
import string

from django.shortcuts import render, redirect
from account.decorators import login_required
from file.models import File
from django.http import FileResponse, JsonResponse, HttpResponse
from django.utils import timezone

from folder.models import Folder
from .judgement_function import judge_filepath, format_size
from django.utils.http import urlquote
import os
from account.models import get_user

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = 1


# Create your views here.


@login_required
def upload_file(request):
    if request.method == "POST":
        user = get_user(request)
        try:
            file_obj = request.FILES.get('upload')
        except:
            print('文件不存在')
            return JsonResponse({'code': 401, 'error': '文件不存在'})
        file_type = judge_filepath(file_obj.name.split('.')[-1].lower()) if '.' in file_obj.name else ''
        update_time = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
        file_size = format_size(file_obj.size)
        file_name = file_obj.name
        folder_id = request.POST.get('folder_id')
        try:
            folder = user.folders.get(folder_id=folder_id)
        except:
            print('文件夹不存在')
            return JsonResponse({'code': 402, 'error': '文件夹不存在'})
        file = File.objects.create(file_name=file_name,
                                   folder=folder,
                                   update_time=update_time,
                                   file_size=file_size,
                                   file_type=file_type)
        # TODO: 文件hash
        file_dir = BASE_DIR + '/' + file.file_id
        with open(file_dir, 'wb+') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)
        return JsonResponse({'code': 200})
    elif request.method == 'GET' and DEBUG:
        return render(request, 'upload_file.html')
    else:
        return HttpResponse(status=400)


@login_required
def download_file(request):
    if request.method == "POST":
        user = get_user(request)
        file_id = request.POST.get('file_id')
        try:
            file = user.files.get(file_id=file_id)
        except:
            print('文件不存在')
            return JsonResponse({'code': 401, 'error': '文件不存在'})
        file_name = file.file_name
        file_dir = BASE_DIR + '/' + file.file_id
        file = open(file_dir, 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename={}'.format(urlquote(file_name))
        return response
    elif request.method == 'GET' and DEBUG:
        return render(request, 'download_file.html')
    else:
        return HttpResponse(status=400)


@login_required
def delete_file(request):
    if request.method == "POST":
        data = request.POST
        user = get_user(request)
        file_id = data.get('file_id')
        try:
            file = user.files.get(file_id=file_id)
        except:
            print('文件不存在')
            return JsonResponse({'code': 401, 'error': '文件不存在'})
        file.delete()
        try:
            os.remove(BASE_DIR + '/' + file_id)
        except Exception as e:
            print(e)
        return JsonResponse({'code': 200})
    elif request.method == 'GET' and DEBUG:
        return render(request, 'delete_file.html')
    else:
        return HttpResponse(status=400)
