# Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered
# Copyright (C) 2005 Rob Bradford <rob@robster.org.uk>
# Copyright (C) 2007-8 Robert McQueen <robert.mcqueen@bluelinux.co.uk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#from pglistener import PgListener
from .pglistener import PgListener

import bsddb3.db as bsddb
import os


class NssDb(PgListener):
    def do_write(self, result, target):
        i = 0
        tmp = "%s.tmp.%d" % (target, i)
        while os.path.exists(tmp):
            i += 1
            tmp = "%s.tmp.%d" % (target, i)
        db = bsddb.DB()

        db.open(
            tmp, None,
            bsddb.DB_BTREE,
            bsddb.DB_CREATE|bsddb.DB_TRUNCATE,
            mode=0o644,
        )
        db_keys = self.options['db-keys']

        for index, row in enumerate(result):
            entry = self.do_format(row) + '\0'

            for field in db_keys.keys():
                db.put(bytes(db_keys[field] % row[field], encoding='utf-8'), entry)
                #db.put((db_keys[field] % row[field]).encode('utf-8'), entry)
            db.put(bytes("0%d" % index, encoding='utf-8'), entry)
            #db.put(b"0%d" % index, entry)

        db.sync()
        db.close()
        os.rename(tmp, target)
