# -*- coding: UTF-8 -*-


# Expression
# By: Frederic Peters <fpeters@entrouvert.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Ducoulombier <sebastien.ducoulombier@lesdeveloppementsdurables.com>
#
# Copyright (C) 2004 Entr'ouvert, Frederic Peters & Emmanuel Raviart
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


"""Berkeley DB XML Database Manager Module"""


import sys

import bsddb3.db as db
import dbxml

import expression.core.environs as environs
import expression.core.dataholders as dataholders
import expression.core.html as html
import expression.core.logs as logs

import expression.modules.dbxmlcontainers as dbxmlcontainers


class DbXmlDatabase(dataholders.DataHolder):
    """ A directory-like station that maps to the database environment manager. """
    _environment = None
    _manager = None
    _containers = None
    isUriDirectory = True

    def generateXml(self, layout):
        """ Just generates a page that confirms this station is the database station. """
        layout.append(
            html.html(
                html.body(
                    html.p(
                        "Berkeley DB XML database at %s" % DbXmlDatabase._manager.getHome()
                    )
                )
            )
        )
        return True

    def walkToItem(self, uriPathFragments, command = None, instruction = None):
        """ Returns the next station if the uriPathFragment is a container name. """
        name = uriPathFragments[0]
        if name in DbXmlDatabase._containers:
            item = dbxmlcontainers.DbXmlContainerHolder(
                DbXmlDatabase._containers[name],
                pathFragment = name,
                previous = self,
                parent = self,
                uriPathFragment = name,
            )
            return item, uriPathFragments[1:]
        return super(DbXmlDatabase, self).walkToItem(uriPathFragments, command, instruction)


def __init__():
    """ Opens a Berkeley DB environment and an XmlManager around it.
        Then opens all configured containers.
    """
    DbXmlDatabase._environment = db.DBEnv()
    DbXmlDatabase._environment.set_shm_key(35)
    dbHome = environs.getVar("configuration").getConfigAbsolutePath(
        """yep:module[@name="%s"]/yep:environment/@dbHome""" % __init__.__module__,
        "/var/lib/expression/db"
    )
    DbXmlDatabase._environment.open(
        dbHome, 0
        |db.DB_INIT_LOCK
        |db.DB_INIT_LOG
        |db.DB_INIT_MPOOL
        |db.DB_INIT_REP
        |db.DB_INIT_TXN
        |db.DB_CREATE
        |db.DB_SYSTEM_MEM
        |db.DB_THREAD
        ,
        0
    )
    DbXmlDatabase._manager = dbxml.XmlManager(DbXmlDatabase._environment, dbxml.DBXML_ADOPT_DBENV)
    DbXmlDatabase._containers = {}
    for name in environs.getVar("configuration").getConfigList("""yep:module[@name="%s"]/yep:container/@name""" % __init__.__module__):
        try:
            DbXmlDatabase._containers[name] = DbXmlDatabase._manager.openContainer(
                name, 0
                |db.DB_CREATE
                |dbxml.DBXML_CHKSUM
            )
        except RuntimeError:
            logs.error("Could not open container %s" % name)
            __del__()
            raise

def __del__():
    """ Closes containers and the database environment.
    """
    del DbXmlDatabase._containers
    DbXmlDatabase._environment.close()

