#! /usr/bin/python
# vim: set fileencoding=utf-8 :
# (c) 2009 Marcos Dione <mdione@grulic.org.ar>

# This file is part of satyr.

# satyr 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.

# satyr 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 satyr.  If not, see <http://www.gnu.org/licenses/>.

# dbus
import dbus
import dbus.mainloop.qt
import dbus.service

# std python
import sys

# local
from satyr.common import BUS_NAME, ConfigurableObject
from satyr.player import Player
from satyr.playlist import PlayList
from satyr.collection import Collection
from satyr.collaggr import CollectionAggregator
from satyr import utils
import satyr

def main ():
    app, args= satyr.createApp ()

    dbus.mainloop.qt.DBusQtMainLoop (set_as_default=True)
    bus= dbus.SessionBus ()
    busName= dbus.service.BusName (BUS_NAME, bus=bus)

    # synthetize a config
    config= ConfigurableObject ('MainWindow')
    config.configValues= (
        ('skin', str, 'default'),
        )
    config.loadConfig ()

    # if the command line is not default, use it
    skin= str (args.getOption ("skin"))
    if skin!="":
        config.skin= skin

    # do the import magic
    # TODO: add the user's app dir to sys.path so we can load skins from there
    mod= utils.import_ ('satyr.skins.'+config.skin)
    mw= mod.MainWindow ()
    config.saveConfig ()

    collaggr= CollectionAggregator (app, busName=busName, busPath='/collaggr')
    if collaggr.collsNo==0:
        print "no collections, picking from args"
        for index in xrange (args.count ()):
            path= args.arg (index)

            # paths must be bytes, not ascii or utf-8
            path= utils.qstring2path (path)

            collection= Collection (app, path, busName=busName, busPath="/collection_%04d" % index)
            collaggr.append (collection)

    for collection in collaggr.collections:
        collection.scanBegins.connect (mw.scanBegins)
        collection.scanFinished.connect (mw.scanFinished)
        # they're loaded by the CollAggr
        # collection.loadOrScan ()
        mw.collectionAdded ()

    playlist= PlayList (app, collaggr, busName=busName, busPath='/playlist')
    player= Player (app, playlist, busName, '/player')
    player.finished.connect (app.quit)

    mw.connectUi (player)
    mw.show ()

    return app.exec_ ()

if __name__=='__main__':
    sys.exit (main ())

# end
