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

from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404, render
from django.views.decorators.csrf import csrf_exempt
from mtp.apps.trainings.models import TrainingSession

from ..forms import AvatarForm


@csrf_exempt
def user(request, user_uuid, session_uuid=None):
    user_obj = get_user_model().objects.get(id=user_uuid)

    if request.method == 'POST':
        if 'first_name' in request.POST:
            first_name = request.POST['first_name']
            user_obj.first_name = first_name
        if 'last_name' in request.POST:
            last_name = request.POST['last_name']
            user_obj.last_name = last_name
        if 'mail' in request.POST:
            mail = request.POST['mail']
            user_obj.email = mail

        if 'business' in request.POST:
            business = request.POST['business']
            user_obj.business = business
        if 'dr' in request.POST:
            user_obj.dr = request.POST['dr']

        avatarForm = AvatarForm(request.POST, request.FILES)

        if avatarForm.is_valid():
            new_photo = avatarForm.save()
            user_obj.photo = new_photo
            user_obj.photos.add(new_photo)

        user_obj.save()

    if session_uuid is not None:
        session = get_object_or_404(TrainingSession, pk=session_uuid)
        notes = user_obj.note_set.filter(training_session=session)
    else:
        notes = user_obj.note_set.all()

    return render(
        request=request,
        template_name='api/json/user.json',
        context=dict(locals(), user=user_obj),  # from dimitri with love
        content_type='application/json',
    )
