#!/usr/bin/python3
# vim: set et ts=4 sw=4:
#    Copyright 2016-2017 Angelo Naselli <anaselli@linux.it>
#
#    dnfdragora is a graphical package management tool based on libyui 
#    python bindings
#
#    dnfdragora is an external manatools module
#
#    License: GPLv3
#

import sys
import os
import gettext

if __name__ == "__main__":

    # We need to call this as early as possible because
    # command-line help strings are translated
    gettext.install('dnfdragora', localedir='/usr/share/locale', names=('ngettext',))

    import argparse

    parser = argparse.ArgumentParser(prog='dnfdragora', usage=_('%(prog)s [options]'))
    ui_select_parser = parser.add_mutually_exclusive_group()
    # libyui pass through arguments
    ui_select_parser.add_argument('--gtk', help=_('start using yui GTK+ plugin implementation'), action='store_true')
    ui_select_parser.add_argument('--ncurses', help=_('start using yui ncurses plugin implementation'), action='store_true')
    ui_select_parser.add_argument('--qt', help=_('start using yui Qt plugin implementation'), action='store_true')
    parser.add_argument('--fullscreen', help=_('use full screen for dialogs'), action='store_true')

    # Application arguments
    parser.add_argument('--group-icons-path', nargs='?', help=_('force a new path for group icons (instead of /usr/share/icons)'))
    parser.add_argument('--images-path', nargs='?', help=_('force a new path for all the needed images (instead of /usr/share/dnfdragora/images)'))
    parser.add_argument('--locales-dir', nargs='?', help=_('directory containing localization strings (developer only)'))

    parser.add_argument('--install',     nargs='+', help=_('install packages'))
    parser.add_argument('--update-only', help=_('show updates only dialog'), action='store_true')
    parser.add_argument('--version',     help=_('show application version and exit'), action='store_true')
    parser.add_argument('--exit',        help=_('force dnfdaemon dbus services used by dnfdragora to exit'), action='store_true')
    args = parser.parse_args()

    # Bypass backend auto-detection: set MUI_BACKEND from --gtk/--ncurses/--qt
    if args.gtk:
        os.environ['MUI_BACKEND'] = 'gtk'
    elif args.ncurses:
        os.environ['MUI_BACKEND'] = 'ncurses'
    elif args.qt:
        os.environ['MUI_BACKEND'] = 'qt'

    # Change localedir if "--locales-dir" option is specified
    if args.locales_dir:
        gettext.install('dnfdragora', localedir=args.locales_dir, names=('ngettext',))

    from gi.repository import GLib
    import logging
    logger = logging.getLogger('dnfdragora')

    import dnfdragora.ui as ui
    import dnfdragora.dialogs as dialogs
    import dnfdragora.misc as misc

    options = {}
    if args.update_only:
        options['update_only'] = True
    if args.group_icons_path:
        options['group_icons_path'] = args.group_icons_path
    if args.images_path:
        options['images_path'] = args.images_path
    if args.install:
        options['install'] = args.install
    if args.exit :
        misc.dbus_dnfsystem('Exit')
    elif args.version:
        import dnfdragora.version
        print (_("%(prog)s %(NL)sversion: %(version)s%(NL)ssite: %(site)s"%
                 {'prog'   :'dnfdragora',
                  'version': dnfdragora.version.__version__,
                  'site'   : "https://github.com/manatools/dnfdragora",
                  'NL'     : "\n"}))
    else:
        main_gui = None
        try:
            main_gui = ui.mainGui(options)
            main_gui.handleevent()
        except Exception as e:
            logger.error("Unexpected error: %s", e, exc_info=True)
            try:
                dialogs.warningMsgBox({
                    'title': _("Sorry"),
                    "text": _("Error occurred:%(NL)s%(error)s") % {'NL': "\n", 'error': str(e)},
                    "richtext": False,
                })
            except Exception:
                pass
        finally:         
            logger.info("Closing dnfdragora")
