"""Helpers for maintainers of kofa sites.

XXX: This stuff might go into a separate package, but right
     now it is too less for a complete package.
"""
import sys
from ZODB.scripts.analyze import report, analyze
from zope.component.hooks import setSite
from zope.component import getUtility
from zope.catalog.interfaces import ICatalog
from zope.intid.interfaces import IIntIds

def db_analyze(args=None):
    """Run the analyze tool from ZODB package.
    """
    if args is None:
        args = sys.argv[1:]

    path = None
    if len(args) > 0:
        path = args[0]
    else:
        print
        print "Analyze a ZODB file and print statistics"
        print "about contained objects, sizes, etc."
        print
        print "Usage: %s <path-to-Data.fs>" % sys.argv[0]
        print
        sys.exit(0)

    report(analyze(path))

def update_catalog(site, cat_name, objects=[], func=None):
    """Update a catalog.

    Put `objects` or objects delivered by `func()` into the catalog
    registered under `cat_name` in `site`.

    Objects to be catalogued must be 'located', i.e. they must have a
    __name__ and __parent__ (because they are adapted to
    IKeyReference).

    You can pass in objects as some iterable or as a function that is
    called to deliver the set of objects to be catalogued.

    A function takes precedence over object lists.
    """
    setSite(site)
    cat = getUtility(ICatalog, name=cat_name)
    intids = getUtility(IIntIds, context=cat)
    if func is not None:
        objects = func()
    for ob in objects:
        doc_id = intids.queryId(ob, None)
        if doc_id is None:
            doc_id = intids.register(ob)
        cat.index_doc(doc_id, ob)
    return cat
