from typing import Union

from annoying.decorators import render_to
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.http import HttpRequest, Http404, HttpResponseRedirect, HttpResponse

from library.forms import PersonForm
from library.models import Person


@render_to("library/person-edit-page.html")
def edit_person(request: HttpRequest, uuid: str) -> Union[dict, HttpResponse]:  # noqa
    try:
        person = Person.objects.get(uuid=uuid)
        form = (
            PersonForm(instance=person)
            if request.method == "GET"
            else PersonForm(request.POST, files=request.FILES, instance=person)
        )
        if form.is_valid():
            # Save the form data in the database, automatically saves files
            recorded = form.save(commit=True)
            # Use the messages application to display a message on the next view.
            messages.success(request, f"{recorded} was successfully updated.")
            return HttpResponseRedirect("")
        return {"person": person, "form": form}
    except (ObjectDoesNotExist, MultipleObjectsReturned):
        # Ask Django view system to render the 404 page.
        raise Http404()
