import logging
import os

from django.conf import settings as s
from django.db import transaction
from django.db.models.signals import pre_delete, post_delete
from django.dispatch import receiver

from epdb.models import Node, Edge, EPModel

logger = logging.getLogger(__name__)


@receiver(pre_delete, sender=Node)
@transaction.atomic
def delete_orphan_edges(sender, instance, **kwargs):
    # check if the node that is about to be deleted is the only start node
    for edge in Edge.objects.filter(start_nodes=instance):
        if edge.start_nodes.count() == 1:
            edge.delete()

    # same for end_nodes
    for edge in Edge.objects.filter(end_nodes=instance):
        # check if the node that is about to be deleted is the only start node
        if edge.end_nodes.count() == 1:
            edge.delete()


@receiver(post_delete, sender=EPModel)
def delete_epmodel_files(sender, instance, **kwargs):
    # Delete the files on disk for the deleted model
    mod_uuid = str(instance.uuid)

    for f in os.listdir(s.MODEL_DIR):
        if f.startswith(mod_uuid):
            logger.info(f"Deleting {os.path.join(s.MODEL_DIR, f)}")
            os.remove(os.path.join(s.MODEL_DIR, f))
