import random
import string

from django.http import HttpResponse
from django.shortcuts import render
from account.decorators import login_required
from .models import Folder
from file.models import File
import json

# Create your views here.
DEBUG = 1


@login_required
def get_first_folder(request):
    if request.method == 'POST':
        # 获取所有根文件夹id
        folders = Folder.objects.filter(father_folder=None)
        response = []
        for i in folders:
            response.append([i.folder_name, i.folder_id])
        return HttpResponse(json.dumps(response), status=200)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'folder_list.html')
    else:
        return HttpResponse(status=400)


# 在根目录下列出所有文件夹与文件
@login_required
def folder_list(request):
    if request.method == 'POST':
        data = request.POST
        # 获取所有文件夹
        folders = Folder.objects.filter(father_folder__folder_id=data['folder_id'])
        files = File.objects.filter(folder__folder_id=data['folder_id'])
        response = []
        for i in folders:
            response.append(['folders', i.folder_name, i.folder_id])
        for i in files:
            response.append(['files', i.file_name, i.file_id, i.file_path, i.file_id, i.update_time, i.file_type, i.file_size])
        return HttpResponse(json.dumps(response), status=200)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'folder_list.html')
    else:
        return HttpResponse(status=400)


# 父文件夹id 子文件夹名字
# 增文件夹
@login_required
def add_folder(request):
    if request.method == 'POST':
        data = request.POST
        folder_id_random = ''.join(random.sample(string.digits, 8))
        father_folder = Folder.objects.filter(folder_id=data['father_folder_id']).get()
        print(data)
        if not father_folder:
            # 查无此文件夹
            return HttpResponse(status=421)
        else:
            if 'folder_name' in data:
                print('yes')
            Folder.objects.create(folder_id=folder_id_random,
                                  folder_name=data.get("folder_name"),
                                  father_folder=father_folder)
            return HttpResponse(status=200)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'add_folder.html')
    else:
        return HttpResponse(status=400)


# 删除文件夹
@login_required
def delete_folder(request):
    if request.method == 'POST':
        data = request.POST
        folder = Folder.objects.filter(folder_id=data['folder_id']).get()
        if not folder:
            # 查无此文件夹
            return HttpResponse(status=421)
        else:
            folder.delete()
            return HttpResponse(status=200)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'delete_folder.html')
    else:
        return HttpResponse(status=400)
