#!/usr/bin/env 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 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()

    # 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 KeyError as e:
            logger.error("KeyError: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except ValueError as e:
            logger.error("ValueError: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except NameError as e:
            logger.error("NameError: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except AttributeError as e:
            logger.error("AttributeError: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except TypeError  as e:
            logger.error("TypeError: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except ui.UIError as e:
            logger.error("UI Error: %s ", e)
            dialogs.warningMsgBox({'title' : _("Sorry"), "text": _("Error occurred:%(NL)s%(error)s")%{'NL': "\n",'error' : str(e)}})
        except GLib.Error as err:
            logger.error(_('dnfdaemon client failure [%s]'), err)
        except:
            logger.error("Unexpected error: %s ", sys.exc_info()[0])
        finally:
            if (main_gui is not None) :
                if main_gui.running :
                    main_gui.backend.quit()

            import yui
            yui.YDialog.deleteAllDialogs()
            # next line seems to be a workaround to prevent the qt-app from crashing
            # see https://github.com/libyui/libyui-qt/issues/41
            yui.YUILoader.deleteUI()
            logger.info("Closing dnfdragora")
