from iconolab.models import Image, AnnotationRevision, Annotation
from haystack import signals
from django.db import models
from iconolab.signals.handlers import revision_created, revision_accepted
import logging

logger = logging.getLogger(__name__)

# update / create new index when a new revision is accepted
# Then update images tags related to this revision
class RevisionSignalProcessor(signals.BaseSignalProcessor):
	
	def setup(self):
		revision_created.connect(self.handle_revision, sender=AnnotationRevision)
		revision_accepted.connect(self.handle_revision, sender=AnnotationRevision)

	def handle_revision(self, **kwargs):
		revision_instance = kwargs.get("instance", None)
		if revision_instance and revision_instance.state in [AnnotationRevision.ACCEPTED]:
			annotation = revision_instance.annotation
			image_annotation = revision_instance.annotation.image
			self.handle_save(Annotation, annotation) 
			self.handle_save(Image, image_annotation)##useful for tag		

	def teardown(self):
		revision_accepted.disconnect(self.handle_accepted_revision, sender=AnnotationRevision)