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
from django.contrib.auth.models import User
import json
import os

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":
        try:
            file_obj = request.FILES.get('upload')
            file_type = judge_filepath(file_obj.name.split('.')[-1].lower())
            file_folder = request.POST.get('file_path')
            update_time = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
            file_size = format_size(file_obj.size)
            file_name = file_obj.name
            save_path = BASE_DIR + '/' + file_folder
            file_path = file_folder + file_name
            file_id_1 = ''.join(random.sample(string.digits, 8))
            File.objects.create(file_id=file_id_1,
                                file_name=file_name,
                                folder=Folder.objects.filter(folder_id=request.POST.get('folder_id')).get(),
                                file_path=file_path,
                                update_time=update_time,
                                file_size=file_size,
                                file_type=file_type)
            with open(save_path + file_name, 'wb+') as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
            return HttpResponse(status=200)
        except Exception as e:
            print(e)
            return HttpResponse(status=401)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'upload_file.html')
    else:
        return HttpResponse(status=400)


@login_required
def download_file(request):
    if request.method == "POST":
        print(request)
        file_path = request.POST.get('file_path')
        file_name = file_path.split('/')[-1]
        file_dir = BASE_DIR + '/' + file_path
        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':
        if 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
        file_path = data.get('file_path')
        try:
            file = File.objects.filter(file_path=file_path, file_id=data.get('file_id')).get()
        except Exception as e:
            print(e)
        else:
            if file:
                file.delete()
                try:
                    os.remove(BASE_DIR + '//' + file_path)
                except Exception as e:
                    print(e)
                return HttpResponse(status=200)

            else:
                return HttpResponse(status=421)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'delete_file.html')
    else:
        return HttpResponse(status=400)
