#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#       Copyright (C) 2010, Joel B. Mohler <joel@kiwistrawberry.us>
#
#  Distributed under the terms of the GNU General Public License (GPL)
#                  http://www.gnu.org/licenses/
##############################################################################

# set up the PyQt API modifications
# this is forced by PyQtBindings
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

import sys
import baker
import datetime
import pyhacc.reports as reports
from fuzzyparsers import *
from PyQt4 import QtCore, QtGui

from pyhacc.PyHaccLib import *
from pyhacc.PyHaccMainWindow import *

# Default the Session (the source of all sqlite data) to nothing.
# This will most likely be assigned in a call to global_kwargs
Session = None

def init_session_maker(conn):
    global Session
    if conn == "sqlite://":
        # special case the in-memory database
        Session = SessionSource(conn,2)  # create data
    else:
        Session = SessionSource(conn)

def global_kwargs(kwargs):
    if kwargs.has_key("conn"):
        init_session_maker(kwargs['conn'])
        del kwargs['conn']

@baker.command
def initdb(conn,level=1):
    s = SessionSource(conn,create_level=level)

@baker.command
def report(report=None,format='csv',outfile=None,pagesize=None,**kwargs):
    """
    Outputs a report.
    
    :param report: The class name of the report from reports.py (if None show a list of available reports)
    :param format: The format of the report output, possible options are 'csv' and 'pdf'.  'html' will be coming.
    :param outfile: The name of the output file name.  This is only supported with 'pdf' so far.
    :param pagesize: The page size with pdf output.  Examples include 'letter', 'landscape_letter', 'A4', 'B3' and 'landscape_A5'.
    """
    global_kwargs(kwargs)

    if report is None:
        for r in reports.report_classes:
            print "{0:22}:  {1}".format(r.__name__, r.name)
            for x in r.prompt_order:
                print "\t{0:16}:  {1}".format(x, getattr(r,x).label)
            print
        return

    report_type = getattr(reports,report)
    b = report_type(Session)
    b.construct(**kwargs)
    if format == 'csv' and outfile is None:
        b.csv(sys.stdout)
    elif format == 'pdf':
        if outfile is None: raise ValueError( "The outfile must be specified for pdf output.")
        b.pdf(outfile,pagesize)
    elif format == 'geraldo':
        if outfile is None: raise ValueError( "The outfile must be specified for pdf output.")
        b.geraldo(outfile,pagesize)

@baker.command
def util(**kwargs):
    global_kwargs(kwargs)

    Utilities(Session)

@baker.command(default=True)
def gui(**kwargs):
    app = QtGui.QApplication(sys.argv)
    app.setOrganizationName("Mohler")
    app.setOrganizationDomain("kiwistrawberry.us")
    app.setApplicationName("PyHacc")

    if not kwargs.has_key("conn"):
        from qtalchemy.dialogs import multi_auth_dialog
        if multi_auth_dialog(parent=None,init_session_maker=init_session_maker, init_db=initdb) != QtGui.QDialog.Accepted:
            return

    global_kwargs(kwargs)

    mainwindow = MainWindow(Session=Session)
    mainwindow.show()
    app.exec_()

if __name__ == "__main__":
    baker.run()
