import os
import logging
import humanize
from tempfile import mkstemp
from shutil import copyfile

from django.core import serializers
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.files.uploadhandler import TemporaryFileUploadHandler

from .tasks import process_message
#from .tasks import test_fail

log = logging.getLogger(__name__)



# @csrf_exempt
# def fail(request):
#     test_fail.delay(1, 2)
#     return JsonResponse({'success': True}, safe=False)


@csrf_exempt
@require_http_methods(["POST"])
def submit(request):
    # always upload into a file
    request.upload_handlers = [TemporaryFileUploadHandler(request)]

    body = request.body
    if not body or len(body) < 1:
        return HttpResponse('Bad request: no data', status=400)

    msg_file = request.FILES['file']
    if not msg_file:
        return HttpResponse('Bad request: no file', status=400)

    msg_size = humanize.naturalsize(msg_file.size, gnu=True)
    log.debug('message file size: {}'.format(msg_size))

    _, tmpfile = mkstemp(suffix='.eml', prefix='markup_', dir=None, text=False)
    log.debug('copy message file from {} to {}'.format(msg_file.temporary_file_path(), tmpfile))
    copyfile(msg_file.temporary_file_path(), tmpfile)
    os.chmod(tmpfile, 0o666)

    process_message.delay(tmpfile)

    return JsonResponse({'success': True}, safe=False)
