'''artlaasya signals'''

from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save, pre_delete

try:
    from django.utils.text import slugify
except ImportError:
    try:
        from django.template.defaultfilters import slugify
    except ImportError:
        print("Unable to import `slugify`.")
except:
    print("Unable to import `slugify`.")

from decimal import Decimal

from artlaasya.utils import is_django_version_greater_than, delete_uploaded_file

from artlaasya.models import (Artist,
                              ArtistRatchet,
                              Genre,
                              Artwork,
                              ArtworkRatchet,
                              Event,
                              EventRatchet)



DJANGO_SAVE_UPDATEABLE = is_django_version_greater_than(1, 4)


@receiver(pre_save, sender=Artist)
def slugify__artist(sender, instance, slugify=slugify, **kwargs):
    """
    Manages the uniquely numbered suffix for `name`.
    Artist [`first_name` + `last_name` + suffix] --> `slug`.
    """
    name_fields_changed = ('first_name' in instance.changed_fields  or
                           'last_name' in instance.changed_fields)
    
    if (name_fields_changed or not instance.slug):
        _name = instance.__str__().lower()
        _ratchet, _created = ArtistRatchet.ratchets.get_or_create(name=_name)
        _incremented_suffix = _ratchet.suffix + 1
        _ratchet.suffix = _incremented_suffix
        _ratchet.save()
        _suffix = str.zfill(str(_incremented_suffix), 3)
        instance.slug = slugify('-'.join([_name, _suffix]))


@receiver(post_save, sender=Artist)
def deactivate_artworks_of_inactive_artist(sender, instance, created, **kwargs):
    """
    Ensures that all artworks of an artist are deactivated when artist is
    deactivated.
    """
    is_active_field_changed = ('is_active' in instance.changed_fields)
    
    if (is_active_field_changed and not instance.is_active):
        for _artwork in instance.artworks_authored.all():
            if _artwork.is_active:
                _artwork.is_active = False
                if DJANGO_SAVE_UPDATEABLE:
                    _artwork.save(update_fields=['is_active'])
                else:
                    _artwork.save()


@receiver(pre_save, sender=Artist, dispatch_uid="d__a_b")
def delete__artist_biography(sender, instance, **kwargs):
    """
    If file already exists, but new file uploaded, delete existing file.
    """
    biography_field_changed = ('biography' in instance.changed_fields)
    
    if biography_field_changed:
        previous_file = instance.get_field_diff('biography')[0]
        if previous_file:
            delete_uploaded_file(previous_file.path)