#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from json import dumps

from core import output
from core.config import CONFIG

from requests import post

from twisted.internet.threads import deferToThread
from twisted.python.log import msg

class Output(output.Output):

    def start(self):
        self.debug = CONFIG.getboolean('output_redisdb', 'debug', fallback=False)
        host = CONFIG.get('output_redisdb', 'host')
        self.password = CONFIG.get('output_redisdb', 'password')
        keyname = CONFIG.get('output_redisdb', 'keyname', fallback='siphoney')
        self.url = 'https://{}/lpush/{}'.format(host, keyname)

    def stop(self):
        pass

    def write(self, event):
        payload = dumps(event, sort_keys=True)
        headers = {
            b'Authorization': 'Bearer {}'.format(self.password),
            b'Content-Type': b'application/json'
        }

        if self.debug:
            msg(payload)

        d = deferToThread(post, self.url, data=payload, headers=headers, timeout=5)
        d.addCallback(self._on_response)
        d.addErrback(self._on_error)

    def _on_response(self, response):
        if self.debug and response.status_code != 200:
            msg('[REST] Response code: {}'.format(response.status_code))

    def _on_error(self, failure):
        msg('[REST] REST error: {}'.format(failure))
