#!/usr/bin/env python

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

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

# gnome-abrt
import gnome_abrt

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):
        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()

    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()
    #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(sys.argv)
    sys.exit(exit_code)
