#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This application is released under the GNU General Public License 
# v3 (or, at your option, any later version). You can find the full 
# text of the license under http://www.gnu.org/licenses/gpl.txt
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license.
#_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
#!v3.6~mickyz(c)2013

from utils import prefs

import optparse
parser = optparse.OptionParser(
    usage='%s [option] [dir/file/url]' % prefs.appExec)
parser.add_option('-n', '--new', action='store_true', default=False,
    help='start new instance')
parser.add_option('-r', '--rebuild', action='store_true',
    help='rebuild cache for given dir')
parser.add_option('-u', '--unset', action='store_true',
    help='unset prefs to defaults')
parser.add_option('-v', '--version', action='store_true',
    help='print version')
opts, args = parser.parse_args()
prefs.cmdLine = opts, args

if opts.rebuild:
    from utils import format
    format.getTags(args[0] if args else '')
    exit()
elif opts.unset:
    prefs.pickleSave(prefs.filePrefs, {})
    #try: shutil.rmtree('~', '.gstreamer-0.10')
    #except: pass
    exit()
elif opts.version:
    print "v3.6~mickyz(c)2013"
    exit()

elif not opts.new:
    """ If application is already running, set the tracklist from args """
    import dbus
    try:
        dbusName = 'org.mpris.%s' % prefs.appExec
        dbusSession = dbus.SessionBus()
        activeServices = dbusSession.get_object(
            'org.freedesktop.DBus','/org/freedesktop/DBus').ListNames()
        if dbusName in activeServices:
            if args: dbus.Interface(dbusSession.get_object(dbusName,'/TrackList'),
                'org.freedesktop.MediaPlayer').SetTracks(args,True)
            exit()
        dbusSession.close()
    except Exception, err:
        print err

import gettext
gettext.textdomain(prefs.appExec)
gettext.bindtextdomain(prefs.appExec, '/usr/share/locale')

from gui.player import GtkWindow
window = GtkWindow()

def atExit():
    prefs.save()
def onInterrupt(window):
    import mods
    mods.postQuitMsg()
    #!emitted at Ctrl+C/SIGTERM
    #signal.alarm(0)

#import atexit
import signal
#atexit.register(atExit)
signal.signal(signal.SIGINT,  lambda sig, frame: onInterrupt(window))
signal.signal(signal.SIGTERM, lambda sig, frame: onInterrupt(window))

window.atInit()
