#!/usr/bin/python3
# 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 locale
import logging
import signal
import sys

# pygobject
#pylint: disable=C0411, C0413
import gi
gi.require_version('Gio', '2.0')
gi.require_version('GLib', '2.0')
gi.require_version('GObject', '2.0')
gi.require_version('Gtk', '3.0')
gi.require_version('Pango', '1.0')
#pylint: disable=E0611, C0411, C0413
from gi.repository import Gtk
#pylint: disable=E0611, C0411, C0413
from gi.repository import GLib
#pylint: disable=E0611, C0411, C0413
from gi.repository import Gio

# gnome-abrt
#pylint: disable=C0413, C0412
import gnome_abrt
gnome_abrt.init()

#pylint: disable=C0413
from gnome_abrt.views import OopsWindow
#pylint: disable=C0413
from gnome_abrt.controller import Controller
#pylint: disable=C0413
from gnome_abrt.signals import glib_sigchld_signal_handler
#pylint: disable=C0413
from gnome_abrt.problems import MultipleSources
#pylint: disable=C0413
from gnome_abrt.dbus_problems import (get_standard_problems_source,
                                      get_foreign_problems_source)
#pylint: disable=C0413
from gnome_abrt.errors import UnavailableSource
#pylint: disable=C0413
from gnome_abrt.l10n import _, C_
#pylint: disable=C0413
from gnome_abrt.config import get_configuration
from gnome_abrt.wrappers import show_events_list_dialog

GNOME_ABRT_APPLICATION_ID = 'org.freedesktop.GnomeAbrt'
GNOME_ABRT_INTERFACE = 'org.freedesktop.GnomeAbrt'
GNOME_ABRT_OBJECT_PATH = '/org/freedesktop/GnomeAbrt'
GNOME_ABRT_URL_POOL_CAPACITY = 10

class OopsApplication(Gtk.Application):

    def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id=GNOME_ABRT_APPLICATION_ID,
                                 flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)

        self.all_sources = None
        self.gnome_settings = None
        # pylint: disable=W0105
        '''
        Again a trick to make xgettext think we are C language and emit the
        translators comment correctly.
        See: bugs.launchpad.net/intltool/+bug/377872
        // Translators: This is a description of --verbose command line option
        // displayed when a user runs: `gnome-abrt --help'
        _("Be verbose")
        '''
        self.add_main_option('verbose',
                             ord('v'),
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE,
                             _('Be verbose'),
                             None)
        # pylint: disable=W0105
        '''
        // Translators: This is a description of --problem command line option
        // displayed when a user runs: `gnome-abrt --help'
        _("Selected problem ID")
        '''
        self.add_main_option('problem',
                             ord('p'),
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING,
                             _('Selected problem ID'),
                             'PROBLEM')

    def _bind_to_gsettings(self, conf):
        def set_time_format(conf, gsettings):
            clck_fmt = None
            try:
                clck_fmt = gsettings.get_value('clock-format').get_string()
            # What exception types is less general?
            #pylint: disable=W0703
            except Exception as ex:
                logging.exception(ex)
                return

            if clck_fmt == '24h':
                conf['T_FMT'] = '%k:%M'
                conf['D_T_FMT'] = '%Y-%m-%d %k:%M'
            else:
                conf['T_FMT'] = '%l:%M %p'
                conf['D_T_FMT'] = '%Y-%m-%d %l:%M %p'

        def settings_changed(settings, key, conf):
            if key == 'clock-format':
                set_time_format(conf, settings)

        if self.gnome_settings is None:
            self.gnome_settings = Gio.Settings(
                    schema='org.gnome.desktop.interface')
            self.gnome_settings.connect(
                    'changed', settings_changed, conf)

        conf.add_option('T_FMT',
                default_value=locale.nl_langinfo(locale.T_FMT))
        conf.add_option('D_T_FMT',
                default_value=locale.nl_langinfo(locale.D_T_FMT))
        set_time_format(conf, self.gnome_settings)

    def do_command_line(self, *args, **kwargs):
        command_line, *_ = args
        options = command_line.get_options_dict().end().unpack()
        configuration = get_configuration()

        if 'verbose' in options:
            logging.getLogger().setLevel(logging.DEBUG)

        for option in options:
            if option in configuration:
                configuration[option] = options[option]

        self.activate()

        return 0

    #pylint: disable=W0221
    def do_activate(self):
        try:
            windows = self.get_windows()
            if windows:
                windows[0].present()
            else:
                conf = get_configuration()
                conf.add_option("all_problems", default_value=False)
                self._bind_to_gsettings(conf)

                sources = []
                try:
                    sources.append(
                          get_standard_problems_source())
                except UnavailableSource as ex:
                    logging.warning(str(ex))

                if not sources:
                    raise UnavailableSource(None, None,
                            message="No available problem source.")

                # pylint: disable=W0105
                '''
                This is a trick to make xgettext think we are C language
                and emit the translators comment correctly.  It's a bug
                in xgettext that it recognizes Python files only after
                their .py extension, there is no way to force the format.
                See: bugs.launchpad.net/intltool/+bug/377872
                // Translators: a list header, "My" is a shortcut for "My bugs"
                _("My")
                '''
                self.all_sources = [(_("My"), MultipleSources(sources))]

                try:
                    # pylint: disable=W0105
                    '''
                    The same trick as above:
                    // Translators: a list header, a shortcut for "System
                    // bugs". In this context "System" may be an adjective
                    // or a genitive noun, as required by your language.
                    C_("bugs", "System")
                    '''
                    self.all_sources.append((C_("bugs", "System"),
                                get_foreign_problems_source()))
                except UnavailableSource as ex:
                    logging.warning(str(ex))

                controller = Controller(self.all_sources,
                                        glib_sigchld_signal_handler)
                main_window = OopsWindow(self, self.all_sources, controller)
                main_window.show_all()
                self.add_window(main_window)
        #pylint: disable=W0703
        except Exception as ex:
            logging.exception(ex)
            sys.exit(1)

    #pylint: disable=W0221
    def do_startup(self):
        Gtk.Application.do_startup(self)

        Gtk.Window.set_default_icon_name(GNOME_ABRT_APPLICATION_ID)

        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_accels_for_action("app.quit", ["<Control>q"])

    #pylint: disable=W0613
    def on_action_prefrences(self, action, parameter):
        windows = self.get_windows()
        if windows:
            show_events_list_dialog(windows[0])
        else:
            show_events_list_dialog()

    #pylint: disable=W0613
    def on_action_about(self, action, parameter):
        #pylint: disable=E1120
        dialog = Gtk.AboutDialog.new()
        dialog.set_version(gnome_abrt.VERSION)
        dialog.set_logo_icon_name(GNOME_ABRT_APPLICATION_ID)
        dialog.set_program_name(_("Problem Reporting"))
        dialog.set_copyright("Copyright © 2019 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://github.com/abrt/gnome-abrt")
        dialog.set_authors(["aboobed <0otibi0@gmail.com>",
                            "Allan Day <allanpday@gmail.com>",
                            "Bastien Nocera <hadess@hadess.net>",
                            "Chris Lockfort <clockfort@csh.rit.edu>",
                            "Daniel Aleksandersen <code@daniel.priv.no>",
                            "Denys Vlasenko <dvlasenk@redhat.com>",
                            "Elad Alfassa <elad@fedoraproject.org>",
                            "Francesco Frassinelli <fraph24@gmail.com>",
                            "Jakub Filák <filak.jakub@gmail.com>",
                            "Jiri Moskovčák <moskovcak@gmail.com>",
                            "Martin Milata <mmilata@redhat.com>",
                            "Matěj Habrnál <mhabrnal@redhat.com>",
                            "Marek Bryša <marek.brysa@gmail.com>",
                            "Michael Catanzaro <mcatanzaro@gnome.org>",
                            "Michal Toman <michal.toman@gmail.com>",
                            "Rafał Lużyński <digitalfreak@lingonborough.com>",
                            "Richard Marko <rmarko@fedoraproject.org>"])
        #dialog.set_artists(artists)
        #dialog.set_translator_credits(_("translator-credits"))

        windows = self.get_windows()
        if windows:
            dialog.set_transient_for(windows[0])

        dialog.run()
        dialog.destroy()

    #pylint: disable=W0613
    def on_action_quit(self, action, parameter):
        self.quit()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, lambda signum, frame: sys.exit(1))
    get_configuration().add_option('problem', default_value=None)
    OopsApplication().run(sys.argv)
