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

"""

import shutil

from django.contrib.gis.db import models
from django.core.exceptions import ObjectDoesNotExist

from konova.models import BaseResource, AbstractDocument, generate_document_file_upload_path
from konova.utils.message_templates import REVOCATION_REMOVED


class Revocation(BaseResource):
    """
    Holds revocation data e.g. for intervention objects
    """
    date = models.DateField(null=True, blank=True, help_text="Revocation from")
    legal = models.ForeignKey("Legal", null=False, blank=False, on_delete=models.CASCADE, help_text="Refers to 'Widerspruch am'", related_name="revocations")
    comment = models.TextField(null=True, blank=True)

    def delete(self, *args, **kwargs):
        # Make sure related objects are being removed as well
        try:
            self.document.delete(*args, **kwargs)
        except ObjectDoesNotExist:
            # No file to delete
            pass

        super().delete()

    @property
    def intervention(self):
        return self.legal.intervention


class RevocationDocument(AbstractDocument):
    """
    Specializes document upload for revocations with certain path
    """
    instance = models.OneToOneField(
        Revocation,
        on_delete=models.CASCADE,
        related_name="document",
    )
    file = models.FileField(
        upload_to=generate_document_file_upload_path,
        max_length=1000,
    )

    @property
    def intervention(self):
        """
        Shortcut for opening the related intervention

        Returns:
            intervention (Intervention)
        """
        return self.instance.legal.intervention

    def delete(self, *args, **kwargs):
        """
        Custom delete functionality for RevocationDocuments.
        Removes the folder from the file system if there are no further documents for this entry.

        Args:
            *args ():
            **kwargs ():

        Returns:

        """
        revoc_docs, other_intervention_docs = self.intervention.get_documents()

        # Remove the file itself
        super().delete(*args, **kwargs)

        if not self.file:
            # If (for reasons) no file path has been added to the entry, we act as if the file did not exist
            raise ObjectDoesNotExist

        # Always remove 'revocation' folder if the one revocation we just processed is the only one left
        folder_path = self.file.path.split("/")
        if revoc_docs.count() == 0:
            try:
                shutil.rmtree("/".join(folder_path[:-1]))
            except FileNotFoundError:
                # Revocation subfolder seems to be missing already
                pass

        if other_intervention_docs.count() == 0:
            # If there are no further documents for the intervention, we can simply remove the whole folder as well!
            try:
                shutil.rmtree("/".join(folder_path[:-2]))
            except FileNotFoundError:
                # Folder seems to be missing already
                pass