import json
import logging

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

from staff.lib.decorators import auth_by_tvm_only
from staff.person.forms import ExportPersonInfoForm

from staff.budget_position.controllers import export_person_value_streams_controller


logger = logging.getLogger(__name__)


@csrf_exempt
@require_http_methods(['POST'])
@auth_by_tvm_only(['review'])
def export_person_value_streams_view(request):
    try:
        form = ExportPersonInfoForm(json.loads(request.body))
    except ValueError:
        logger.info('Invalid JSON received', exc_info=True)
        return JsonResponse({}, status=400)

    if not form.is_valid():
        return JsonResponse(data=form.errors_as_dict(), status=400)

    return JsonResponse(data=export_person_value_streams_controller(form.cleaned_data['persons']), status=200)
