from django.db.models.signals import post_delete, pre_save
from django.dispatch import receiver

from .models import SubProductVersion
from .release_assets import RELEASE_FILE_BY_URL_FIELD


def _stored_release_file_name(version, file_field):
    release_file = getattr(version, file_field)
    return release_file.name if release_file else ""


def _delete_release_file_from_disk(version, file_field):
    release_file = getattr(version, file_field)
    if release_file:
        release_file.delete(save=False)


@receiver(pre_save, sender=SubProductVersion)
def delete_replaced_or_cleared_release_files(sender, instance, **kwargs):
    if not instance.pk:
        return
    try:
        previous = SubProductVersion.objects.get(pk=instance.pk)
    except SubProductVersion.DoesNotExist:
        return
    for file_field in RELEASE_FILE_BY_URL_FIELD.values():
        old_name = _stored_release_file_name(previous, file_field)
        new_name = _stored_release_file_name(instance, file_field)
        if old_name and old_name != new_name:
            _delete_release_file_from_disk(previous, file_field)


@receiver(post_delete, sender=SubProductVersion)
def delete_release_files_on_version_delete(sender, instance, **kwargs):
    for file_field in RELEASE_FILE_BY_URL_FIELD.values():
        _delete_release_file_from_disk(instance, file_field)
