#!/usr/bin/env python
#
# This file is part of Panucci.
# Copyright (c) 2008-2009 The Panucci Audiobook and Podcast Player Project
#
# Panucci 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 3 of the License, or
# (at your option) any later version.
#
# Panucci 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 Panucci.  If not, see <http://www.gnu.org/licenses/>.
#

app_version = '0.3.9'

import dbus
import dbus.glib
import logging
import os.path
import sys

sys.path.insert(0, '/opt/panucci/lib/')

from optparse import OptionParser

_ = lambda s: s

usage = 'usage: %prog [options] FILE'
parser = OptionParser(usage=usage, version='%prog ' + app_version)
parser.add_option('-q', '--queue', action='store', type='string',
    dest='queue_filename', help='Add FILE to the queue', metavar='FILE')
parser.add_option('-d', '--debug', action='store_true', default=False,
    dest='debug', help='Enable verbose logging')
opts, args = parser.parse_args()

if len(args) > 1 or ( opts.queue_filename and len(args) ):
    parser.print_help()
    sys.exit(1)

local_module_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', 'src')
if os.path.isdir(local_module_dir):
    sys.path.append(local_module_dir)

from panucci import util
filepath = util.build_full_path(args[0] if len(args) else opts.queue_filename)

session_bus = dbus.SessionBus()
try:
    remote_object = session_bus.get_object(
        'org.panucci.panucciInterface', '/panucciInterface' )
    print _('Found panucci instance already running, will try to use it...')
except dbus.exceptions.DBusException:
    remote_object = None

if remote_object is None:
    from panucci import panucci
    log_level = logging.DEBUG if opts.debug else logging.ERROR
    logging.basicConfig(level=log_level)
    panucci.app_version = app_version
    panucci.run( filename=filepath ) 
else:
    if filepath is not None:
        if opts.queue_filename is not None:
            remote_object.queue_file( filepath )
        else:
            remote_object.play_file( filepath )

    remote_object.show_main_window()

