#!/usr/bin/env python
# coding=UTF-8

## Copyright (C) 2012 ABRT team <abrt-devel-list@redhat.com>
## Copyright (C) 2001-2005 Red Hat, Inc.

## This program 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.

## This program 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 this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA  02110-1335  USA

import os
import sys
import logging
import signal
from argparse import ArgumentParser

# pygobject
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gio
from gi.repository import GObject

# gnome-abrt
import gnome_abrt
from gnome_abrt.l10n import _
from gnome_abrt.wrappers import show_events_list_dialog

class OopsApplication(Gtk.Application):

    def __init__(self):
        super(OopsApplication, self).__init__()

        conf = gnome_abrt.get_configuration()
        conf.add_option("all_problems", default_value=False)

        sources = []
        try:
            sources.append(gnome_abrt.DBusProblemSource())
        except gnome_abrt.UnavailableSource as e:
            logging.warning(e.message)

        # TODO : really ? move it somewhere else ...
        self.gcontext = GLib.main_context_default()
        try:
            # TODO : pass the directory over command line
            sources.append(gnome_abrt.DirectoryProblemSource(os.path.join(GLib.get_user_cache_dir(), "abrt/spool"), context=self.gcontext))
        except gnome_abrt.UnavailableSource as e:
            logging.warning(e.message)

        if len(sources) == 0:
            raise gnome_abrt.UnavailableSource("No available problem source.")

        self.source = gnome_abrt.MultipleSources(*sources)

    def do_activate(self):
        try:
            self.window = gnome_abrt.OopsWindow(self, self.source, gnome_abrt.Controller(self.source))
            self.window.connect("delete-event", self.on_window_delete_event)
            self.window.show_all()
        except Exception as e:
            logging.exception(e.message)
            sys.exit(1)

    def do_startup(self):
        Gtk.Application.do_startup(self)

        menu = Gio.Menu()
        menu.append(_("_Preferences"), "app.preferences")
        menu.append(_("_About"), "app.about")
        menu.append(_("_Quit"), "app.quit")

        action = Gio.SimpleAction.new("preferences", None)
        action.connect("activate", self.on_action_prefrences);
        self.add_action(action);

        action = Gio.SimpleAction.new("about", None)
        action.connect("activate", self.on_action_about);
        self.add_action(action);

        action = Gio.SimpleAction.new("quit", None)
        action.connect("activate", self.on_action_quit);
        self.add_action(action);

        self.set_app_menu(menu)

    def on_action_prefrences(self, action, parameter):
        show_events_list_dialog(self.window)

    def on_action_about(self, action, parameter):
        dialog = Gtk.AboutDialog()
        dialog.set_icon_name("abrt");
        #dialog.set_version(VERSION);
        dialog.set_logo_icon_name("abrt");
        dialog.set_program_name("ABRT");
        dialog.set_copyright("Copyright © 2012 Red Hat, Inc");
        dialog.set_license(
                "This program is free software; you can redistribut"
                "e 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 Li"
                "cense, or (at your option) any later version.\n\nThis program is distrib"
                "uted in the hope that it will be useful, but WITHOUT ANY WARRANTY; witho"
                "ut even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICU"
                "LAR PURPOSE.  See the GNU General Public License for more details.\n\nYo"
                "u should have received a copy of the GNU General Public License along wi"
                "th this program.  If not, see <http://www.gnu.org/licenses/>.");
        dialog.set_wrap_license(True);
        dialog.set_website("https://fedorahosted.org/abrt/");
        dialog.set_authors(["ABRT Team"]);
        #dialog.set_artists(artists);
        #dialog.set_translator_credits(_("translator-credits"));
        dialog.run()
        dialog.destroy()

    def on_action_quit(self, action, parameter):
        self.quit()

    def on_window_delete_event(self, widget, data):
        self.quit()


if __name__ == "__main__":
    signal.signal(signal.SIGINT, lambda signum, frame: sys.exit(1))

    gnome_abrt.init()

    CMDARGS = ArgumentParser(description = _('View and report application crashes'))
    CMDARGS.add_argument('-v', '--verbose', action='count', help=_('Be verbose'))

    OPTIONS = CMDARGS.parse_args()

    if OPTIONS.verbose > 0:
        logging.getLogger().setLevel(logging.DEBUG)

    app = None
    try:
        app = OopsApplication()
    except gnome_abrt.UnavailableSource as e:
        logging.error(e.message)
        sys.exit(1)

    exit_code = app.run(None)
    sys.exit(exit_code)
