from django.http import HttpResponse


class MessageAfterResponse(HttpResponse):
    """
    An expanded Response class that will allow a message to be sent after a response was to the API caller
    """
    delay = None
    topic = None
    message = None
    subject = None
    source = None

    def __init__(self, content=..., *args, **kwargs):
        self.delay = kwargs.pop('delay', 1)
        self.topic = kwargs.pop('topic', None)
        self.message = kwargs.pop('message', None)
        self.subject = kwargs.pop('subject', None)
        self.source = kwargs.pop('source', None)

        if isinstance(content, dict):
            from rest_framework.renderers import JSONRenderer
            content = JSONRenderer().render(content)
            kwargs['content_type'] = 'application/json'

        super().__init__(content, *args, **kwargs)

    def close(self):
        import logging, time
        time.sleep(self.delay)
        try:  # wrap this in case of issues
            from messaging.topic_providers import MessageWrapper
            from messaging.models import Message
            if self.source is not None:  # tracks message
                Message.publish_message(topic=self.topic, message=self.message, subject=self.subject,
                                        source=self.source)
            else:  # just publish, no tracks
                MessageWrapper.get().publish(topic=self.topic, message=self.message, subject=self.subject)
            logging.warning(self.topic)
            logging.warning(self.message)
        except Exception as e:
            logging.error(e)
        super().close()