#!/usr/local/bin/python3.4

import sys
import signal
import os
import locale
import gettext

# Make sure we'll find the pygobject module, even in JHBuild
sys.path.insert(1, '/usr/local/lib/python3.4/site-packages')
# Make sure we'll find the gnomemusic module, even in JHBuild
sys.path.insert(1, '/usr/local/lib/python3.4/site-packages')

import argparse
import logging
import gi
from gi.repository import Gio
import gnomemusic

localedir = '/usr/local/share/locale'
srcdir = os.path.abspath(os.path.join(os.path.dirname(gnomemusic.__file__), '..'))
if os.path.exists(os.path.join(srcdir, 'gnome-music.doap')):
    print('Running from source tree, using local files')
    pkgdatadir = os.path.join(srcdir, 'data')
    libgd_libdir = os.path.join(srcdir, 'libgd', '.libs')
    libgd_typelibdir = os.path.join(srcdir, 'libgd')
    if not os.environ.get('GSETTINGS_SCHEMA_DIR'):
        os.environ['GSETTINGS_SCHEMA_DIR'] = pkgdatadir
else:
    pkgdatadir = '/usr/local/share/gnome-music'
    libgd_libdir = '/usr/local/lib/gnome-music'
    libgd_typelibdir = '/usr/local/lib/gnome-music/girepository-1.0'

# We use our own libgd.so, so let gi.repository find it
gi.require_version('GIRepository', '2.0')
from gi.repository import GIRepository
GIRepository.Repository.prepend_search_path(libgd_typelibdir)
GIRepository.Repository.prepend_library_path(libgd_libdir)


def install_excepthook():
    """ Make sure we exit when an unhandled exception occurs. """
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk
    old_hook = sys.excepthook

    def new_hook(etype, evalue, etb):
        old_hook(etype, evalue, etb)
        while Gtk.main_level():
            Gtk.main_quit()
        sys.exit()
    sys.excepthook = new_hook

if __name__ == "__main__":
    install_excepthook()

    parser = argparse.ArgumentParser()
    parser.add_argument('-d', "--debug", action="store_true", default=False, dest="debug")
    args = parser.parse_args()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(levelname)s\t%(message)s',
                            datefmt='%H:%M:%S')
        # Gtk hates "-d" switch, so lets drop it
        if '-d' in sys.argv:
            sys.argv.remove("-d")
        if '--debug' in sys.argv:
            sys.argv.remove("--debug")
    else:
        logging.basicConfig(level=logging.WARN,
                            format='%(asctime)s %(levelname)s\t%(message)s',
                            datefmt='%H:%M:%S')

    locale.bindtextdomain('gnome-music', localedir)
    locale.textdomain('gnome-music')
    gettext.bindtextdomain('gnome-music', localedir)
    gettext.textdomain('gnome-music')

    resource = Gio.resource_load(os.path.join(pkgdatadir, 'gnome-music.gresource'))
    Gio.Resource._register(resource)

    from gnomemusic.application import Application

    app = Application()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    exit_status = app.run(sys.argv)
    sys.exit(exit_status)
