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

from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt

from mtp.apps.accounts.models import MTPUser
from mtp.apps.trainings.models import TrainingSession

from ..models import Document, Note


@csrf_exempt
def save_notes(request, user_uuid):

    session_id = request.POST.get('session_id', None)
    session = get_object_or_404(TrainingSession, pk=session_id)
    user = get_object_or_404(MTPUser, pk=user_uuid)  # pylint: disable=W0621

    note_type = request.POST.get('type')
    if 'id_doc' in request.POST:
        id_doc = request.POST['id_doc']
        document = get_object_or_404(Document, pk=id_doc)
    else:
        document = None

    text = request.POST.get('text')
    page = request.POST.get('page', 0)
    x = request.POST.get('x', 0)  # pylint: disable=C0103
    y = request.POST.get('y', 0)  # pylint: disable=C0103
    w = request.POST.get('w', 0)  # pylint: disable=C0103
    h = request.POST.get('h', 0)  # pylint: disable=C0103

    note = Note.objects.create(  # pylint: disable=W0612
        user=user, session=session,
        note_type=note_type, document=document,
        text=text, page=int(page),
        coord_x=float(x), coord_y=float(y),
        width=float(w), height=float(h),
    )

    return render_to_response(
        'api/json/note.json', locals(),
        content_type='application/json',
        context_instance=RequestContext(request),
    )


@csrf_exempt
def update_notes(request, user_uuid, note_uuid):

    if request.POST.get('_method', '') == 'DELETE':
        Note.objects.filter(pk=note_uuid).delete()

        return render_to_response(
            'api/json/note.json', locals(),
            content_type='application/json',
            context_instance=RequestContext(request),
        )

    user = get_object_or_404(MTPUser, pk=user_uuid)  # pylint: disable=W0612,W0621
    note = get_object_or_404(Note, pk=note_uuid)

    page = request.POST.get('page', 0)
    x = request.POST.get('x', 0)  # pylint: disable=C0103
    y = request.POST.get('y', 0)  # pylint: disable=C0103
    w = request.POST.get('w', 0)  # pylint: disable=C0103,W0612
    h = request.POST.get('h', 0)  # pylint: disable=C0103,W0612
    text = request.POST.get('text')
    note_type = request.POST.get('type')

    note.page = page
    note.coord_x = float(x)
    note.coord_y = float(y)
    note.text = text
    note.note_type = note_type
    note.save()

    return render_to_response(
        'api/json/note.json', locals(),
        content_type='application/json',
        context_instance=RequestContext(request),
    )
