#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Event producer for trigger lib
#
# Author    : Pierre-Elliott Bécue <becue@crans.org>
# License   : GPLv3
# Date      : 18/05/2014

"""
This is the message producer. It's standalone lib.
"""

import cmb
import cPickle
import pika

# Clogger
import cranslib.clogger as clogger

# Trigger features
import gestion.secrets_new as secrets
import gestion.config.trigger as trigger_config

logger = clogger.CLogger("trigger", "EventProducer", trigger_config.log_level, trigger_config.debug)

class EventProducer(cmb.BasicProducer):
    """
    EventProducer tracker
    """
    def __init__(self, app_id):
        """Extended

        """
        logger.info("Starting trigger EventProducer program for app %s…", app_id)
        trigger_password = secrets.get('rabbitmq_trigger_password')
        credentials = pika.PlainCredentials(trigger_config.user, trigger_password)
        super(EventProducer, self).__init__(url=trigger_config.master, exchange_name="trigger", app_id=app_id, port=trigger_config.port, credentials=credentials, ssl=trigger_config.ssl)
        self._connection = self.connect()
        self.get_chan()

    def send_message(self, routing_key, body):
        """Sends basic message with app_id and body

        """
        try:
            logger.info("Sending message %s with routing_key %s.", body, routing_key)
            body = cPickle.dumps(body)
            self._channel.basic_publish(exchange=self._exchange_name,
                                        routing_key=routing_key,
                                        body=body,
                                        properties=pika.BasicProperties(
                                            delivery_mode=2,
                                            app_id=self._app_id,
                                        ))
        except:
            print "Failure in trigger.event"
            raise

    def announce(self, body):
        """Feature to send message without giving routing_key

        """
        self.send_message("trigger.event", body)
