"""
Simple Graylog HTTP Graylog Extended Log Format (GELF) logger.
"""

from io import BytesIO
from json import dumps
from time import time

from core import output
from core.config import CONFIG

from zope.interface import implementer

from twisted.internet import reactor, ssl
from twisted.web import client, http_headers
from twisted.web.client import FileBodyProducer
from twisted.web.iweb import IPolicyForHTTPS


class Output(output.Output):
    def start(self):
        self.url = CONFIG.get('output_graylog', 'url').encode('utf8')
        contextFactory = WhitelistContextFactory()
        self.agent = client.Agent(reactor, contextFactory)

    def stop(self):
        pass

    def write(self, event):
        gelf_message = {
            'version': '1.1',
            'host': event['sensor'],
            'timestamp': time(),
            'short_message': dumps(event),
            'level': 1,
        }
        self.postentry(gelf_message)

    def postentry(self, entry):
        headers = http_headers.Headers(
            {
                b'Content-Type': [b'application/json'],
            }
        )
        body = FileBodyProducer(BytesIO(dumps(entry).encode('utf8')))
        self.agent.request(b'POST', self.url, headers, body)


@implementer(IPolicyForHTTPS)
class WhitelistContextFactory:
    def creatorForNetloc(self, hostname, port):
        return ssl.CertificateOptions(verify=False)
