from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django.dispatch import receiver
import logging
from .models import Item, Tag
from .search import load_index, delete_item, update_item
import shutil
from .views.image import base_item

# Get a logger instance
clogger = logging.getLogger("CACHING")

__pre_remove__ = None
__pre_add__ = None


@receiver(post_delete, sender=Item)
def item_delete(instance, **kwargs):
    # delete cached xnails
    clogger.info('Deleting Xnails stored in "%s".', base_item.__cache_image_folder__(None, instance.rel_path))
    shutil.rmtree(base_item.__cache_image_folder__(None, instance.rel_path), True)
    # delete index entry
    ix = load_index()
    delete_item(ix, instance)


@receiver(post_save, sender=Item)
def item_save(instance, **kwargs):
    ix = load_index()
    update_item(ix, instance)


@receiver(post_save, sender=Tag)
@receiver(post_delete, sender=Tag)
def tag_change(instance, **kwargs):
    ix = load_index()
    update_item(ix, instance.item)
