#!/usr/bin/python
# This file is part of pybliographer
# 
# Copyright (C) 1998-2006 Frederic GOBRY
# Email : gobry@pybliographer.org
# 	   
# 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.
# 

""" Main module for pybliographic.

This module handles the set of opened documents.
"""

import sys
import os

from PyblioUI.Gtk import Document
from Pyblio import Registry

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-P", "--profile", dest="profile",
                  action="store_true", default=False,
                  help="profile the application")

parser.add_option("-s", "--store", dest="store",
                  action="store", default="file",
                  help="default store used when creating a new database")

parser.add_option("-c", "--create", dest="create",
                  action="store", default=None,
                  help="create the database with the specified schema instead of opening it")

(options, files) = parser.parse_args()


from gettext import gettext as _

# We log all the events both to the console, and to a graphical
# handler.
import logging

base = logging.getLogger('pyblio')
hdlr = logging.StreamHandler()

fmtr = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
hdlr.setFormatter(fmtr)

base.addHandler(hdlr)

from PyblioUI.Gtk import Logs

visual = Logs.Handler()
base.addHandler(visual)

# The internal exceptions need to go through the handler too
def handle_exception(type, value, traceback):
    r = base.makeRecord('pyblio', logging.ERROR,
                        None, None,
                        _('An unexpected error occured'),
                        (), (type, value, traceback))
    
    base.handle(r)
    return

sys.excepthook = handle_exception

base.setLevel(logging.INFO)


# We search the known RIP files
Registry.parse(Registry.RIP_dirs['system'])

try:
    Registry.parse(Registry.RIP_dirs['user'])
except OSError:
    pass

for d in os.environ.get('PYBLIO_RIP_DIRS', '').split(':'):
    if d:
        Registry.parse(d)


from PyblioUI import Gtk as UI

docs = []

def _on_close (doc):

    docs.remove (doc)
    if not docs: UI.exit ()

    return

def _on_quit (doc):

    for d in docs[:]:
        d.close ()

    return


if files:
    for f in files:
        d = Document.Document()

        if options.create:
            from Pyblio import Store

            fmt = Store.get(options.store)
            schema = Registry.getSchema(options.create)

            d.create(f, fmt, schema)

        else:
            d.open (f, None)
        
        d.register ('close', _on_close)
        d.register ('quit', _on_quit)
        
        docs.append(d)

else:
    d = Document.Document()
    d.register ('close', _on_close)
    d.register ('quit', _on_quit)
    
    docs.append (d)

    d.create()


if options.profile:
    import hotshot
    p = hotshot.Profile('+pybliographic.prof')
    p.runcall(UI.run)

else:
    UI.run ()
