
from __future__ import absolute_import

from time import sleep

from core import output
from core.config import CONFIG

from rethinkdb import r

from twisted.python.log import msg


class Output(output.Output):

    def start(self):
        host = CONFIG.get('output_rethinkdblog', 'host', fallback='localhost')
        port = CONFIG.getint('output_rethinkdblog', 'port', fallback=28015)
        self.db = CONFIG.get('output_rethinkdblog', 'db', fallback='siphoney')
        password = CONFIG.get('output_rethinkdblog', 'password', raw=True)
        self.table = CONFIG.get('output_rethinkdblog', 'table', fallback='events')

        try:
            self.connection = r.connect(host=host, port=port, password=password)

            if self.db not in r.db_list().run(self.connection):
                r.db_create(self.db).run(self.connection)
            for _ in range(50):  # ~5 seconds max
                if self.db in r.db_list().run(self.connection):
                    break
                sleep(0.1)
            if self.table not in r.db(self.db).table_list().run(self.connection):
                r.db(self.db).table_create(self.table).run(self.connection)

        except r.RqlError as err:
            msg('output_rethinkdblog: Error: {}'.format(err.message))

    def stop(self):
        if getattr(self, 'connection', None):
            self.connection.close()

    def write(self, event):
        try:
            r.db(self.db).table(self.table).insert(event).run(self.connection)
        except r.RqlRuntimeError as err:
            msg('output_rethinkdblog: Error: {}'.format(err.message))
