"""This module holds the api-related views of the ``metaplans`` app"""

import json

from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt

from mtp.apps.api.constants import BAD_REQUEST_HTTP_RESPONSE
from mtp.apps.trainings.models import CurrentSession, TrainingSession

from ..models import Metaplan, MetaplanProposition


@csrf_exempt
def metaplan_save(request, user_uuid=None, metaplan_uuid=None):

    if request.method != 'POST':
        return BAD_REQUEST_HTTP_RESPONSE

    if 'session_id' in request.POST:
        current_session = get_object_or_404(TrainingSession, pk=request.POST['session_id'])
    else:
        current_session = CurrentSession.objects.first().session

    try:
        metaplan_data = json.loads(request.POST['json'])
    except KeyError:
        return BAD_REQUEST_HTTP_RESPONSE

    if metaplan_uuid:
        metaplan = get_object_or_404(Metaplan, pk=metaplan_uuid)
        metaplan.name = metaplan_data['title']
        metaplan.propositions.all().delete()
    else:
        metaplan = Metaplan(name=metaplan_data['title'], session=current_session)

    metaplan.save()

    for proposition in metaplan_data['data']:
        MetaplanProposition.objects.create(
            metaplan=metaplan,
            text=proposition['msg'],
            group=proposition['type'],
            user=get_user_model().objects.get(
                id=proposition['user_id']
            ),
        )

    return HttpResponse('{"id": "%s"}' % metaplan.id, content_type='application/json')
