import json
import logging

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from staff.lib.decorators import available_by_tvm, available_for_external

from staff.achievery.forms.create_achievement import CreateAchievementForm
from staff.achievery.tasks import create_achievement_task

logger = logging.getLogger(__name__)


@require_POST
@csrf_exempt
@available_for_external
def validate_create_achievement(request):
    try:
        data = json.loads(request.body.decode())
    except ValueError:
        logger.warning('Got invalid JSON')
        return JsonResponse({'status': 'ERROR'}, status=400)

    answers = {ans['slug']: ans['value'] for ans in data['questions']}

    form = CreateAchievementForm(icon_required=False, data=answers)

    if not form.is_valid():
        return JsonResponse(
            {
                'status': 'ERROR',
                'errors': dict(form.errors),
            },
            status=200,
        )

    return JsonResponse({'status': 'OK'}, status=200)


@require_POST
@csrf_exempt
@available_by_tvm(['forms'])
def create_achievement(request):
    try:
        data = json.loads(request.body.decode())
    except ValueError:
        logger.warning('Got invalid JSON')
        return JsonResponse({}, status=400)

    create_achievement_task.delay(data)
    return JsonResponse({}, status=200)
