import os
import urllib.parse
import subprocess

from django.conf import settings
from django.http import FileResponse
from django.shortcuts import render
from rest_framework.decorators import api_view, parser_classes
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser
from rest_framework import status


def index(request):
    return render(request, 'index.html')


@api_view(['GET'])
def test(request):
    if request.method == 'GET':
        return Response({"message": "Hello, World!"})


@api_view(['POST'])
@parser_classes([MultiPartParser])
def upload(request):
    file_obj = request.FILES.get('file')
    protocol_name = request.data.get('protocol_name')
    version = request.data.get('version')
    print(protocol_name)
    print(version)
    print(file_obj.name)
    folder_path = os.path.join(settings.BASE_DIR, 'protocol_raw_files', protocol_name, version)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    with open(f'./protocol_raw_files/{protocol_name}/{version}/{file_obj.name}', 'wb+') as destination:
        for chunk in file_obj.chunks():
            destination.write(chunk)
    return Response(status=status.HTTP_200_OK)


@api_view(['GET'])
def download(request):
    protocol_name = request.GET.get('protocol_name')
    version = request.GET.get('version')

    file_path = os.path.join(settings.BASE_DIR, 'protocol_raw_files', protocol_name, version)
    for root, _, files in os.walk(file_path):
        file_path = os.path.join(root, files[1])
        # 适配中文
        file_name = urllib.parse.quote(os.path.basename(file_path))

        response = FileResponse(open(file_path, 'rb'))
        response['Content-Disposition'] = 'inline; filename=' + file_name
        response['Content-Type'] = 'multipart/form-data'
        response['filename'] = file_name
        return response

    return Response(status=status.HTTP_200_OK)


@api_view(['POST'])
def restart_device(request):
    try:
        subprocess.Popen(f'sudo docker restart {settings.DEVICE_CONTAINER_NAME}', shell=True)
    except Exception as e:
        print(e)
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return Response(status=status.HTTP_200_OK)
 