
from time import mktime
from datetime import datetime

from core import output
from core.config import CONFIG

from rethinkdb import r


def iso8601_to_timestamp(value):
    return mktime(datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f+00:00Z').timetuple())


class Output(output.Output):
    # noinspection PyAttributeOutsideInit
    def start(self):
        db = CONFIG.get('output_rethinkdblog', 'db')
        self.table = CONFIG.get('output_rethinkdblog', 'table')
        self.connection = r.connect(
            host=CONFIG.get('output_rethinkdblog', 'host'),
            port=CONFIG.getint('output_rethinkdblog', 'port', fallback=28015),
            db=db,
            user=CONFIG.get('output_rethinkdblog', 'user', raw=True, fallback='admin'),
            password=CONFIG.get('output_rethinkdblog', 'password', raw=True, fallback='')
        )
        try:
            r.db_create(db).run(self.connection)
            r.db(db).table_create(self.table).run(self.connection)
        except r.RqlRuntimeError:
            pass

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

    def write(self, event):
        event['timestamp'] = iso8601_to_timestamp(event['timestamp'])
        r.table(self.table).insert(event).run(self.connection)
