
from __future__ import absolute_import

from json import dumps
from socket import socket, AF_INET, SOCK_STREAM

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


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

    def start(self):
        timeout = CONFIG.getint('output_socketlog', 'timeout')
        addr = CONFIG.get('output_socketlog', 'address')
        host = addr.split(':')[0]
        port = int(addr.split(':')[1])

        self.sock = socket(AF_INET, SOCK_STREAM)
        self.sock.settimeout(timeout)
        self.sock.connect((host, port))

    def stop(self):
        self.sock.close()

    def write(self, event):
        message = dumps(event, sort_keys=True) + '\n'

        try:
            self.sock.sendall(encode(message))
        except OSError as ex:
            if ex.errno == 32:  # Broken pipe
                self.start()
                self.sock.sendall(encode(message))
            else:
                raise
