#!/usr/bin/env python3
# Copyright (c) 2016 The GNOME Music Developers
#
# GNOME Music 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.
#
# GNOME Music 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 GNOME Music; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# The GNOME Music authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distributed together with GStreamer
# and GNOME Music.  This permission is above and beyond the permissions
# granted by the GPL license by which GNOME Music is covered.  If you
# modify this code, you may extend this exception to your version of the
# code, but you are not obligated to do so.  If you do not wish to do so,
# delete this exception statement from your version.

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/lib/python3.6/site-packages')
# Make sure we'll find the gnomemusic module, even in JHBuild
sys.path.insert(1, '/usr/lib/python3.6/site-packages')

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

localedir = '/usr/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/share/gnome-music'
    libgd_libdir = '/usr/lib/gnome-music'
    libgd_typelibdir = '/usr/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)
