"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 01.09.21

"""
from django.http import FileResponse, HttpRequest, Http404

from konova.forms.modals import RemoveModalForm
from konova.models import AbstractDocument
from konova.utils.message_templates import DOCUMENT_REMOVED_TEMPLATE


def get_document(doc: AbstractDocument):
    """ Returns a document as downloadable attachment

    Args:
        request (HttpRequest): The incoming request
        id (str): The document id

    Returns:

    """
    try:
        return FileResponse(doc.file, as_attachment=True)
    except FileNotFoundError:
        raise Http404()


def remove_document(request: HttpRequest, doc: AbstractDocument):
    """ Renders a form for uploading new documents

    This function works using a modal. We are not using the regular way, the django bootstrap modal forms are
    intended to be used. Instead of View classes we work using the classic way of dealing with forms (see below).
    It is important to mention, that modal forms, which should reload the page afterwards, must provide a
    'reload_page' bool in the context. This way, the modal may reload the page or not.

    For further details see the comments in templates/modal or
    https://github.com/trco/django-bootstrap-modal-forms

    Args:
        request (HttpRequest): The incoming request

    Returns:

    """
    title = doc.title
    form = RemoveModalForm(request.POST or None, instance=doc, request=request)
    return form.process_request(
        request=request,
        msg_success=DOCUMENT_REMOVED_TEMPLATE.format(title),
    )