
from __future__ import absolute_import

from json import dumps

from core import output
from core.config import CONFIG
from core.tools import to_bytes

from confluent_kafka import Producer

from twisted.python.log import msg


class Output(output.Output):

    def start(self):
        self.topic = CONFIG.get('output_kafka', 'topic', fallback='siphoney')
        self.debug = CONFIG.getboolean('output_kafka', 'debug', fallback=False)

        self.producer = Producer({
            'bootstrap.servers': '{}:{}'.format(
                CONFIG.get('output_kafka', 'host', fallback='localhost'),
                CONFIG.get('output_kafka', 'port', fallback=9092)
            ),
            #'sasl.mechanism': 'SCRAM-SHA-256',
            #'security.protocol': 'SASL_SSL',
            #'sasl.username': CONFIG.get('output_kafka', 'username'),
            #'sasl.password': CONFIG.get('output_kafka', 'password')
        })

    def stop(self):
        self.producer.flush()

    def write(self, event):
        self.postentry(event)

    def delivery_callback(self, err, message):
        if err:
            msg('output_kafka: Message failed delivery: {}.'.format(err))
        else:
            if self.debug:
                msg('output_kafka: Message delivered to {} [{}] @ {}'.format(
                    message.topic(), message.partition(), message.offset()
                ))

    def postentry(self, event):
        try:
            self.producer.produce(
                self.topic,
                to_bytes(dumps(event, sort_keys=True)),
                callback=self.delivery_callback
            )
            self.producer.poll(0)
            self.producer.flush()
        except Exception as e:
            msg('Kafka error: {}'.format(e))
