
from time import gmtime, strftime, time

from core import output
from core.config import CONFIG

from slack import WebClient

from twisted.internet import reactor
from twisted.internet.task import deferLater


class Output(output.Output):
    """
    slack output
    """

    def start(self):
        self.slack_channel = CONFIG.get('output_slack', 'channel')
        self.slack_token = CONFIG.get('output_slack', 'token')
        self.delay = CONFIG.getfloat('output_slack', 'delay', fallback=1.2)
        self.sc = WebClient(self.slack_token)
        self.last_sent = 0
        self.requests_list = []

    def stop(self):
        pass

    def write(self, event):
        message = '[{} UTC] [SIPHoney on {}]: {} from {}:{}.'.format(
            strftime('%Y-%m-%d %H:%M:%S', gmtime(event['unixtime'])),
            event['sensor'], event['message'], event['src_ip'], event['dst_port']
        )
        self.post_message(message)

    def post_message(self, message):
        now = time()
        self.requests_list.append(message)
        if now - self.last_sent < self.delay:
            deferLater(reactor, self.delay, self.post_message, message)
            return
        self.last_sent = now
        message = self.requests_list.pop(0)
        self.sc.chat_postMessage(channel=self.slack_channel, text=message)
