#########################################################################
#             GNU HEALTH HOSPITAL MANAGEMENT - GTK CLIENT               #
#                      https://www.gnuhealth.org                        #
#########################################################################
#       The GNUHealth HMIS client based on the Tryton GTK Client        #
#########################################################################
#
# SPDX-FileCopyrightText: 2008-2024 The Tryton Community <info@tryton.org>
# SPDX-FileCopyrightText: 2017-2024 GNU Health Community <info@gnuhealth.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

# This file is part of GNU Health.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

import gettext
import json
import logging
import os
import sys
import threading
import traceback
import webbrowser
from functools import partial
from urllib.parse import parse_qsl, unquote, urlparse

from gi.repository import Gdk, GdkPixbuf, Gio, GLib, Gtk

import gnuhealth.common as common
import gnuhealth.plugins
import gnuhealth.rpc as rpc
import gnuhealth.translate as translate
from gnuhealth.action import Action
from gnuhealth.common import RPCContextReload, RPCException, RPCExecute
from gnuhealth.common.cellrendererclickablepixbuf import (
    CellRendererClickablePixbuf)
from gnuhealth.config import CONFIG, GNUHEALTH_ICON, get_config_dir
from gnuhealth.exceptions import GNUHealthError, GNUHealthServerUnavailable
from gnuhealth.gui.window import Window
from gnuhealth.jsonrpc import object_hook
from gnuhealth.pyson import PYSONDecoder

# GNUHealth block: client version and other related imports
import time
import platform
from gnuhealth.gui.window.activity import Activity
from gnuhealth import __version__
import ast

_ = gettext.gettext
logger = logging.getLogger(__name__)
_PRIORITIES = [getattr(Gio.NotificationPriority, p)
               for p in ('LOW', 'NORMAL', 'HIGH', 'URGENT')]


class Main(Gtk.Application):
    window = None
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

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

        action = Gio.SimpleAction.new('preferences', None)
        action.connect('activate', lambda *a: self.preferences())
        self.add_action(action)
        self.set_accels_for_action('app.preferences', ['<Primary>comma'])

        action = Gio.SimpleAction.new('menu-search', None)
        action.connect(
            'activate', lambda *a: self.global_search_entry.grab_focus())
        self.add_action(action)
        self.set_accels_for_action('app.menu-search', ['<Primary>k'])

        action = Gio.SimpleAction.new('menu-toggle', None)
        action.connect('activate', lambda *a: self.menu_toggle())
        self.add_action(action)
        self.set_accels_for_action('app.menu-toggle', ['<Primary>m'])

        toolbar_variant = GLib.Variant.new_string(
            CONFIG['client.toolbar'] or 'both')
        action = Gio.SimpleAction.new_stateful(
            'toolbar', toolbar_variant.get_type(), toolbar_variant)
        action.connect('change-state', self.on_change_toolbar)
        self.add_action(action)

        def on_change_action_boolean(action, value, key):
            action.set_state(value)
            CONFIG[key] = value.get_boolean()

        for name, key in [
                ('save-tree-width', 'client.save_tree_width'),
                ('save-tree-state', 'client.save_tree_state'),
                ('code-scanner-sound', 'client.code_scanner_sound'),
                ('spell-checking', 'client.spellcheck'),
        ]:
            variant = GLib.Variant.new_boolean(CONFIG[key])
            action = Gio.SimpleAction.new_stateful(name, None, variant)
            action.connect('change-state', on_change_action_boolean, key)
            self.add_action(action)

        action = Gio.SimpleAction.new('tab-previous', None)
        action.connect('activate', lambda *a: self.win_prev())
        self.add_action(action)
        self.set_accels_for_action('app.tab-previous', ['<Primary><Shift>Tab'])

        action = Gio.SimpleAction.new('tab-next', None)
        action.connect('activate', lambda *a: self.win_next())
        self.add_action(action)
        self.set_accels_for_action('app.tab-next', ['<Primary>Tab'])

        action = Gio.SimpleAction.new('search-limit', None)
        action.connect('activate', lambda *a: self.edit_limit())
        self.add_action(action)

        action = Gio.SimpleAction.new('documentation', None)
        action.connect('activate', lambda *a: common.open_documentation())
        self.add_action(action)

        action = Gio.SimpleAction.new('donation', None)
        action.connect('activate', lambda *a: common.open_donation())
        self.add_action(action)

        self._shortcuts = None
        action = Gio.SimpleAction.new('shortcuts', None)
        action.connect('activate', lambda *a: self.shortcuts())
        self.add_action(action)
        self.set_accels_for_action('app.shortcuts', ['<Primary>F1'])

        action = Gio.SimpleAction.new('about', None)
        action.connect('activate', lambda *a: self.about())
        self.add_action(action)

        action = Gio.SimpleAction.new('quit', None)
        action.connect('activate', self.on_quit)
        self.add_action(action)
        self.set_accels_for_action('app.quit', ['<Primary>q'])

        # GNU Health block
        # Add Activity Window action
        action = Gio.SimpleAction.new('activity', None)
        action.connect('activate', lambda *a: self.activity_toggle())
        self.add_action(action)
        self.set_accels_for_action('app.activity', ['<Shift>F12'])

        # GNU Health Command Line focus
        action = Gio.SimpleAction.new('gh_cli', None)
        action.connect('activate', lambda *a: self.gnuhealth_cli())
        self.add_action(action)
        self.set_accels_for_action('app.gh_cli', ['<Primary><Shift>Z'])

        # GNU Health Block: Set Main Menu menubar
        main_menu = Gio.Menu.new()
        file_menu = Gio.Menu.new()
        settings_menu = Gio.Menu.new()
        help_menu = Gio.Menu.new()
        toolbar = Gio.Menu.new()
        main_menu.append_submenu(_("File"), file_menu)
        main_menu.append_submenu(_("Settings"), settings_menu)
        main_menu.append_submenu(_("Help"), help_menu)

        settings_menu.append(_("Preferences..."), 'app.preferences')

        settings_menu.append_submenu(_("Toolbar"), toolbar)
        toolbar.append(_("Default"), 'app.toolbar::default')
        toolbar.append(_("Text and Icons"), 'app.toolbar::both')
        toolbar.append(_("Text"), 'app.toolbar::text')
        toolbar.append(_("Icons"), 'app.toolbar::icons')

        form = Gio.Menu.new()
        settings_menu.append_submenu(_("Form"), form)
        form.append(_("Save Width/Height"), 'app.save-width-height')
        form.append(_("Save Tree State"), 'app.save-tree-state')
        form.append(_("Spell Checking"), 'app.spell-checking')
        form.append(_("Play Sound for Code Scanner"), 'app.code-scanner-sound')

        settings_menu.append(_("Search Limit..."), 'app.search-limit')
        settings_menu.append(_("Email..."), 'app.email')

        help_menu.append(_("Documentation..."), 'app.documentation')
        help_menu.append(_("Keyboard Shortcuts..."), 'app.shortcuts')
        help_menu.append(_("About..."), 'app.about')
        help_menu.append(
            _("Donate to GNU Health") + " " + "\N{heavy black heart}",
            'app.donation')

        file_menu.append(_("Quit"), 'app.quit')

        self.set_menubar(main_menu)

    def do_activate(self):
        if self.window:
            self.window.present()
            return

        self.window = Gtk.ApplicationWindow(application=self)
        title = self.get_main_title()
        self.window.set_title(title)
        self.window.set_default_size(1280, 960)
        self.window.maximize()
        self.window.set_position(Gtk.WindowPosition.CENTER)
        self.window.set_resizable(True)
        self.window.set_icon(GNUHEALTH_ICON)
        self.window.connect("destroy", self.on_quit)
        self.window.connect("delete_event", self.on_quit)
        common.setup_window(self.window)

        # GNU Health
        # Disable title bar
        # self.window.set_titlebar(self.header)
        self.header = Gtk.HeaderBar.new()
        self.header.set_show_close_button(True)
        self.set_title()

        menu = Gtk.Button.new()
        menu.set_relief(Gtk.ReliefStyle.NONE)
        menu.set_image(
            common.IconFactory.get_image(
                'gnuhealth-menu', Gtk.IconSize.BUTTON))
        menu.connect('clicked', self.menu_toggle)
        self.header.pack_start(menu)

        favorite = Gtk.MenuButton.new()
        favorite.set_relief(Gtk.ReliefStyle.NONE)
        favorite.set_image(common.IconFactory.get_image(
            'gnuhealth-bookmarks', Gtk.IconSize.BUTTON))
        self.menu_favorite = Gtk.Menu.new()
        favorite.set_popup(self.menu_favorite)
        favorite.connect('button-press-event', self.favorite_set)
        # self.header.pack_start(favorite)

        # self.set_global_search()
        # self.header.pack_start(self.global_search_entry)

        self.accel_group = Gtk.AccelGroup()
        self.window.add_accel_group(self.accel_group)

        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/New', Gdk.KEY_N, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Save', Gdk.KEY_S, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Duplicate', Gdk.KEY_D,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Delete',
            Gdk.KEY_D, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Next',
            Gdk.KEY_Down, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Previous',
            Gdk.KEY_Up, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Switch View', Gdk.KEY_L,
            Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Close', Gdk.KEY_W, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Reload',
            Gdk.KEY_R, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Attachments', Gdk.KEY_T,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Notes', Gdk.KEY_O,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Relate', Gdk.KEY_R,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Actions',
            Gdk.KEY_E, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Report',
            Gdk.KEY_P, Gdk.ModifierType.CONTROL_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Email', Gdk.KEY_E,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
        Gtk.AccelMap.add_entry(
            '<gnuhealth>/Form/Search', Gdk.KEY_F,
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)

        Gtk.AccelMap.load(os.path.join(get_config_dir(), 'accel.map'))

        self.tooltips = common.Tooltips()

        self.vbox = Gtk.VBox()
        self.window.add(self.vbox)

        self.buttons = {}

        self.info = Gtk.VBox()
        self.vbox.pack_start(self.info, expand=False, fill=True, padding=0)
        self.pane = Gtk.HPaned()
        self.vbox.pack_start(self.pane, expand=True, fill=True, padding=0)
        self.pane.set_position(int(CONFIG['menu.pane']))

        self.menu_screen = None
        self.menu = Gtk.VBox()
        self.menu.set_vexpand(True)
        self.pane.add1(self.menu)

        self.notebook = Gtk.Notebook()
        self.notebook.popup_enable()
        self.notebook.set_scrollable(True)
        self.notebook.connect_after('switch-page', self._sig_page_changt)
        self.pane.add2(self.notebook)

        self.window.show_all()

        self.pages = []
        self.previous_pages = {}
        self.current_page = 0
        self.last_page = 0
        self.dialogs = []

        # Register plugins
        gnuhealth.plugins.register()

        # Initialize GNU Health environment
        # GNUHEALTH CLI
        self.cli = self.statusbar = self.footer_contents = self.footer = None
        self.cli_position = CONFIG['client.cli_position']

        self.init_gnuhealth_env()

        self.set_title()  # Adds username/profile while password is asked
        try:
            common.get_credentials()
        except Exception as exception:
            if not isinstance(exception, GNUHealthError):
                common.error(exception, traceback.format_exc())
            elif exception.faultCode == 'SessionFailed':
                common.message(
                    _("Could not get a session."),
                    msg_type=Gtk.MessageType.ERROR)
            return self.quit()
        self.get_preferences()

        # GNUHealth Block
        # Add connection successful entry to the Activity log
        msg = "Connected to GNU Health Server"
        self.activity_log_entry(msg, 'info')

    def gnuhealth_cli(self):
        self.cli.grab_focus()

    def do_command_line(self, cmd):
        self.do_activate()
        arguments = cmd.get_arguments()
        if len(arguments) > 1:
            url = arguments[1]
            self.open_url(url)
        return True

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)
        common.Logout()
        CONFIG.save()
        Gtk.AccelMap.save(os.path.join(get_config_dir(), 'accel.map'))

    def on_quit(self, *args):
        try:
            if not self.close_pages():
                return True
        except GNUHealthServerUnavailable:
            pass
        rpc.logout()
        self.quit()

    def add_window(self, window):
        super().add_window(window)
        common.setup_window(window)

    def set_global_search(self):
        self.global_search_entry = Gtk.Entry.new()
        self.global_search_entry.set_width_chars(20)
        global_search_completion = Gtk.EntryCompletion()
        global_search_completion.set_match_func(lambda *a: True)
        global_search_completion.set_model(
            Gtk.ListStore(GdkPixbuf.Pixbuf, str, str, int, str))
        pixbuf_cell = Gtk.CellRendererPixbuf()
        global_search_completion.pack_start(pixbuf_cell, expand=True)
        global_search_completion.add_attribute(pixbuf_cell, 'pixbuf', 0)
        text_cell = Gtk.CellRendererText()
        global_search_completion.pack_start(text_cell, expand=True)
        global_search_completion.add_attribute(text_cell, "markup", 1)
        global_search_completion.props.popup_set_width = True

        self.global_search_entry.set_completion(global_search_completion)

        def match_selected(completion, model, iter_):
            model, record_id, model_name = model.get(iter_, 2, 3, 4)
            if model == self.menu_screen.model_name:
                # ids is not defined to prevent to add suffix
                Action.exec_keyword('tree_open', {
                    'model': model,
                    'id': record_id,
                })
            else:
                Window.create(
                    model,
                    res_id=record_id,
                    mode=['form', 'tree'],
                    name=model_name)
            self.global_search_entry.set_text('')
            return True

        global_search_completion.connect('match-selected', match_selected)

        def update(widget, search_text, callback=None):
            def end():
                if callback:
                    callback()
                return False
            if search_text != widget.get_text():
                return end()
            gmodel = global_search_completion.get_model()
            if not search_text or not gmodel:
                gmodel.clear()
                gmodel.search_text = search_text
                return end()
            if getattr(gmodel, 'search_text', None) == search_text:
                return end()

            def set_result(result):
                try:
                    result = result()
                except RPCException:
                    result = []
                if search_text != widget.get_text():
                    if callback:
                        callback()
                    return False
                gmodel.clear()
                for r in result:
                    _, model, model_name, record_id, record_name, icon = r
                    if icon:
                        text = common.to_xml(record_name)
                        pixbuf = common.IconFactory.get_pixbuf(
                            icon, Gtk.IconSize.BUTTON)
                    else:
                        text = '<b>%s:</b>\n %s' % (
                            common.to_xml(model_name),
                            common.to_xml(record_name))
                        pixbuf = None
                    gmodel.append([pixbuf, text, model, record_id, model_name])
                gmodel.search_text = search_text
                # Force display of popup
                widget.emit('changed')
                end()

            RPCExecute(
                'model', 'ir.model', 'global_search', search_text,
                CONFIG['client.limit'], self.menu_screen.model_name,
                context=self.menu_screen.context, callback=set_result)
            return False

        def changed(widget):
            search_text = widget.get_text()
            GLib.timeout_add(300, update, widget, search_text)

        def activate(widget):
            def message():
                gmodel = global_search_completion.get_model()
                if not len(gmodel):
                    common.message(_('No result found.'))
                else:
                    widget.emit('changed')
            search_text = widget.get_text()
            update(widget, search_text, message)

        self.global_search_entry.connect('changed', changed)
        self.global_search_entry.connect('activate', activate)

    def set_title(self, value=''):
        if CONFIG['login.profile']:
            login_info = CONFIG['login.profile']
        else:
            login_info = '%s@%s/%s' % (
                CONFIG['login.login'],
                CONFIG['login.host'],
                CONFIG['login.db'])
        titles = []
        if value:
            titles.append(value)
        titles.append(CONFIG['client.title'])
        self.header.set_title(' - '.join(titles))
        self.header.set_subtitle(login_info)
        try:
            style_context = self.header.get_style_context()
        except AttributeError:
            pass
        else:
            for name in style_context.list_classes():
                if name.startswith('profile-'):
                    style_context.remove_class(name)
            if CONFIG['login.profile']:
                style_context.add_class(
                    'profile-%s' % CONFIG['login.profile'])

    def favorite_set(self, *args):
        if self.menu_favorite.get_children():
            return

        def _action_favorite(widget, id_):
            event = Gtk.get_current_event()
            allow_similar = (
                event.state & Gdk.ModifierType.MOD1_MASK
                or event.state & Gdk.ModifierType.SHIFT_MASK)
            with Window(allow_similar=allow_similar):
                # ids is not defined to prevent to add suffix
                Action.exec_keyword('tree_open', {
                    'model': self.menu_screen.model_name,
                    'id': id_,
                })

        def _manage_favorites(widget):
            Window.create(
                self.menu_screen.model_name + '.favorite',
                mode=['tree', 'form'],
                name=_("Favorites"))
        try:
            favorites = RPCExecute(
                'model',
                self.menu_screen.model_name + '.favorite', 'get',
                process_exception=False)
        except Exception:
            return False
        for id_, name, icon in favorites:
            menuitem = Gtk.MenuItem(label=name)
            menuitem.connect('activate', _action_favorite, id_)
            self.menu_favorite.add(menuitem)
        self.menu_favorite.add(Gtk.SeparatorMenuItem())
        manage_favorites = Gtk.MenuItem(
            label=_("Manage..."),
            use_underline=True)
        manage_favorites.connect('activate', _manage_favorites)
        self.menu_favorite.add(manage_favorites)
        self.menu_favorite.show_all()

    def favorite_unset(self):
        for child in self.menu_favorite.get_children():
            self.menu_favorite.remove(child)

    def on_change_toolbar(self, action, value):
        action.set_state(value)
        option = value.get_string()
        CONFIG['client.toolbar'] = option
        if option == 'default':
            barstyle = False
        elif option == 'both':
            barstyle = Gtk.ToolbarStyle.BOTH
        elif option == 'text':
            barstyle = Gtk.ToolbarStyle.TEXT
        elif option == 'icons':
            barstyle = Gtk.ToolbarStyle.ICONS
        for page_idx in range(self.notebook.get_n_pages()):
            page = self.get_page(page_idx)
            if page.toolbar:
                page.toolbar.set_style(barstyle)

    def edit_limit(self):
        from gnuhealth.gui.window.limit import Limit
        Limit().run()

    def win_next(self):
        page = self.notebook.get_current_page()
        if page == len(self.pages) - 1:
            page = -1
        self.notebook.set_current_page(page + 1)

    def win_prev(self):
        page = self.notebook.get_current_page()
        self.notebook.set_current_page(page - 1)

    def get_preferences(self):
        RPCContextReload()
        try:
            prefs = RPCExecute('model', 'res.user', 'get_preferences', False)
        except RPCException:
            prefs = {}

        targets = [
            common.IconFactory.load_icons,
            common.MODELACCESS.load_models,
            common.MODELHISTORY.load_history,
            common.MODELNOTIFICATION.load_names,
            common.VIEW_SEARCH.load_searches,
        ]
        if CONFIG['thread']:
            threads = []
            for target in targets:
                t = threading.Thread(target=target)
                threads.append(t)
                t.start()
            for t in threads:
                t.join()
        else:
            for target in targets:
                target()

        if prefs and 'language_direction' in prefs:
            translate.set_language_direction(prefs['language_direction'])
            CONFIG['client.language_direction'] = \
                prefs['language_direction']
        self.sig_win_menu(prefs=prefs)
        for action_id in prefs.get('actions', []):
            Action.execute(action_id, {})
        self.set_title(prefs.get('status_bar', ''))
        if prefs and 'language' in prefs:
            translate.setlang(prefs['language'], prefs.get('locale'))
            CONFIG['client.lang'] = prefs['language']
        common.MODELNAME.clear()
        # Set placeholder after language is set to get correct translation
        self.global_search_entry.set_placeholder_text(_("Global Search"))
        CONFIG.save()

    def preferences(self):
        from gnuhealth.gui.window.preference import Preference
        if not self.close_pages():
            return False
        Preference(rpc._USER, self.get_preferences)

    def sig_win_close(self, widget=None):
        self._sig_remove_book(
            widget,
            self.notebook.get_nth_page(self.notebook.get_current_page()))

    def close_pages(self):
        if self.notebook.get_n_pages():
            if not common.sur(
                    _('The following action requires to close all tabs.\n'
                      'Do you want to continue?')):
                return False
        res = True
        while res:
            wid = self.get_page()
            if wid:
                if not wid.sig_close():
                    return False
                res = self._win_del()
            else:
                res = False
        if self.menu_screen:
            self.menu_screen.save_tree_state()
        if self.menu.get_visible():
            CONFIG['menu.pane'] = self.pane.get_position()
        return True

    def about(self):
        from gnuhealth.gui.window.about import About
        About()

    def shortcuts(self):
        if self._shortcuts:
            self._shortcuts.destroy()
        self._shortcuts = window = Gtk.ShortcutsWindow()
        window.set_transient_for(common.get_toplevel_window())
        window.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
        window.set_destroy_with_parent(True)
        self.add_window(window)

        section = Gtk.ShortcutsSection()
        section.props.section_name = 'app'
        section.props.title = _("Application Shortcuts")
        section.props.visible = True

        group = Gtk.ShortcutsGroup()
        group.props.title = _("Global")
        section.add(group)

        for action, title in [
                ('app.preferences', _("Preferences")),
                ('app.menu-search', _("Search menu")),
                ('app.menu-toggle', _("Toggle menu")),
                ('app.tab-previous', _("Previous tab"), ),
                ('app.tab-next', _("Next tab")),
                ('app.shortcuts', _("Shortcuts")),
                ('app.quit', _("Quit")),
        ]:
            shortcut = Gtk.ShortcutsShortcut()
            shortcut.props.title = title
            accels = self.get_accels_for_action(action)
            if accels:
                shortcut.props.accelerator = ' '.join(accels)
                group.add(shortcut)

        window.add(section)

        for name, title, groups in [
                ('entry', _("Edition Shortcuts"), [
                    (_("Text Entries"), [
                        ('<Primary>x', _("Cut selected text")),
                        ('<Primary>c', _("Copy selected text")),
                        ('<Primary>v', _("Paste copied text")),
                        ('Tab', _("Next entry")),
                        ('<Shift>Tab', _("Previous entry")),
                    ]),
                    (_("Relation Entries"), [
                        ('F3', _("Create new relation")),
                        ('F2', _("Open/Search relation")),
                    ]),
                    (_("List Entries"), [
                        ('F4', _("Switch view")),
                        ('F3', _("Create/Select new line")),
                        ('F2', _("Open relation")),
                        ('Delete',
                         _("Mark line for deletion/removal")),
                        ('<Ctrl>Delete', _("Mark line for removal")),
                        ('Insert', _("Unmark line for deletion")),
                    ]),
                ]),
                ('tree', _("List/Tree Shortcuts"), [
                    (_("Move Cursor"), [
                        ('Right', _("Move right")),
                        ('Left', _("Move left")),
                        ('Up', _("Move up")),
                        ('Down', _("Move down")),
                        ('Page_Up', _("Move up of one page")),
                        ('Page_Down', _("Move down of one page")),
                        ('Home', _("Move to top")),
                        ('End', _("Move to bottom")),
                        ('BackSpace', _("Move to parent")),
                    ]),
                    (_("Edition"), [
                        ('<Primary>c', _("Copy selected rows")),
                        ('<Primary>v', _("Insert copied rows")),
                    ]),
                    (_("Selection"), [
                        ('<Ctrl>a <Ctrl>slash', _("Select all")),
                        ('<Shift><Ctrl>a <Shift><Ctrl>slash',
                         _("Unselect all")),
                        ('BackSpace', _("Select parent")),
                        ('space', _("Select/Activate current row")),
                        ('<Shift>space Return',
                         _("Select/Activate current row")),
                        ('<Ctrl>space', _("Toggle selection")),
                    ]),
                    (_("Expand/Collapse"), [
                        ('plus', _("Expand row")),
                        ('minus', _("Collapse row")),
                        ('space', _("Toggle row")),
                        ('<Shift>Left', _("Collapse all rows")),
                        ('<Shift>Right', _("Expand all rows")),
                    ]),
                ]),
        ]:
            section = Gtk.ShortcutsSection()
            section.props.section_name = name
            section.props.title = title
            section.props.visible = True

            for title, shortcuts in groups:
                group = Gtk.ShortcutsGroup()
                group.props.title = title
                section.add(group)

                for accelerator, title in shortcuts:
                    shortcut = Gtk.ShortcutsShortcut()
                    shortcut.props.title = title
                    shortcut.props.accelerator = accelerator
                    group.add(shortcut)

            window.add(section)

        window.show_all()

    def menu_toggle(self, *args):
        if self.menu.get_visible():
            CONFIG['menu.pane'] = self.pane.get_position()
            self.pane.set_position(0)
            self.notebook.grab_focus()
            self.menu.set_visible(False)
        else:
            self.pane.set_position(int(CONFIG['menu.pane']))
            self.menu.set_visible(True)
            if self.menu_screen:
                self.menu_screen.set_cursor()

    def menu_row_activate(self):
        screen = self.menu_screen
        record_id = (
            screen.current_record.id
            if screen.current_record else None)
        # ids is not defined to prevent to add suffix
        return Action.exec_keyword('tree_open', {
            'model': screen.model_name,
            'id': record_id,
        }, warning=False)

    def sig_win_menu(self, prefs=None):
        from gnuhealth.gui.window.view_form.screen import Screen

        if not prefs:
            try:
                prefs = RPCExecute('model', 'res.user', 'get_preferences',
                                   False)
            except RPCException:
                return False

        if self.menu_screen:
            self.menu_screen.save_tree_state()
        for child in self.menu.get_children():
            self.menu.remove(child)

        action = PYSONDecoder().decode(prefs['pyson_menu'])
        view_ids = []
        if action.get('views', []):
            view_ids = [x[0] for x in action['views']]
        elif action.get('view_id', False):
            view_ids = [action['view_id'][0]]
        ctx = rpc.CONTEXT.copy()
        decoder = PYSONDecoder(ctx)
        action_ctx = decoder.decode(action.get('pyson_context') or '{}')
        domain = decoder.decode(action['pyson_domain'])
        screen = Screen(
            action['res_model'], mode=['tree'], view_ids=view_ids,
            domain=domain, context=action_ctx, readonly=True, limit=None,
            row_activate=self.menu_row_activate)
        # Use alternate view to not show search box
        screen.screen_container.alternate_view = True
        screen.switch_view(view_type=screen.current_view.view_type)

        self.menu.pack_start(
            screen.screen_container.alternate_viewport,
            expand=True, fill=True, padding=0)
        treeview = screen.current_view.treeview
        treeview.set_headers_visible(False)

        # Favorite column
        column = Gtk.TreeViewColumn()
        column.name = None
        column._type = None
        favorite_renderer = CellRendererClickablePixbuf()
        column.pack_start(favorite_renderer, expand=False)

        def favorite_setter(column, cell, store, iter_, user_data=None):
            menu = store.get_value(iter_, 0)
            favorite = menu.value.get('favorite')
            if favorite:
                icon = 'gnuhealth-star'
            elif favorite is False:
                icon = 'gnuhealth-star-border'
            else:
                icon = None
            if icon:
                pixbuf = common.IconFactory.get_pixbuf(
                    icon, Gtk.IconSize.MENU)
            else:
                pixbuf = None
            cell.set_property('pixbuf', pixbuf)
        column.set_cell_data_func(favorite_renderer, favorite_setter)

        def toggle_favorite(renderer, path, treeview):
            if treeview.props.window:
                self.toggle_favorite(renderer, path, treeview)
        favorite_renderer.connect(
            'clicked',
            lambda *a: GLib.idle_add(toggle_favorite, *a), treeview)
        # Unset fixed height mode to add column
        treeview.set_fixed_height_mode(False)
        treeview.set_property(
            'enable-grid-lines', Gtk.TreeViewGridLines.NONE)
        treeview.append_column(column)

        screen.search_filter()
        screen.display(set_cursor=True)
        self.menu_screen = screen

    def toggle_favorite(self, renderer, path, treeview):
        store = treeview.get_model()
        iter_ = store.get_iter(path)
        menu = store.get_value(iter_, 0)
        favorite = menu.value.get('favorite')
        if favorite:
            value = False
            method = 'unset'
        elif favorite is False:
            value = True
            method = 'set'
        else:
            return
        try:
            RPCExecute('model', self.menu_screen.model_name + '.favorite',
                       method, menu.id)
        except RPCException:
            return
        menu.value['favorite'] = value
        store.row_changed(path, iter_)
        self.favorite_unset()

    def win_set(self, page):
        current_page = self.notebook.get_current_page()
        page_num = self.notebook.page_num(page.widget)
        page.widget.props.visible = True
        self.notebook.set_current_page(page_num)
        # In order to focus the page
        if current_page == page_num:
            self._sig_page_changt(self.notebook, None, page_num)

    def win_add(self, page, hide_current=False):
        previous_page_id = self.notebook.get_current_page()
        previous_widget = self.notebook.get_nth_page(previous_page_id)
        if previous_widget and hide_current:
            page_id = previous_page_id + 1
        else:
            page_id = -1
        self.previous_pages[page] = previous_widget
        self.pages.append(page)
        hbox = Gtk.HBox(spacing=3)
        if page.icon:
            hbox.pack_start(
                common.IconFactory.get_image(
                    page.icon, Gtk.IconSize.SMALL_TOOLBAR),
                expand=False, fill=False, padding=0)
        name = page.name
        label = Gtk.Label(
            label=common.ellipsize(name.split(' / ')[-1], 20),
            halign=Gtk.Align.START)
        self.tooltips.set_tip(label, page.name)
        self.tooltips.enable()
        hbox.pack_start(label, expand=True, fill=True, padding=0)

        button = Gtk.Button()
        button.set_relief(Gtk.ReliefStyle.NONE)
        button.set_can_focus(False)
        button.add(common.IconFactory.get_image(
            'gnuhealth-close', Gtk.IconSize.MENU))
        self.tooltips.set_tip(button, _('Close Tab'))
        button.connect('clicked', self._sig_remove_book, page.widget)
        hbox.pack_start(button, expand=False, fill=False, padding=0)
        size = Gtk.IconSize.lookup(Gtk.IconSize.MENU)
        button.set_size_request(size.width, size.height)

        hbox.show_all()
        label_menu = Gtk.Label(
            label=page.name, halign=Gtk.Align.START)
        page.widget.props.margin = 3
        self.notebook.insert_page_menu(page.widget, hbox, label_menu, page_id)
        self.notebook.set_tab_reorderable(page.widget, True)
        self.notebook.set_current_page(page_id)

    def _sig_remove_book(self, widget, page_widget):
        for page in self.pages:
            if page.widget == page_widget:
                if not page.widget.props.sensitive:
                    return
                page_num = self.notebook.page_num(page.widget)
                self.notebook.set_current_page(page_num)
                res = page.sig_close()
                if not res:
                    return
        self._win_del(page_widget)

    def _win_del(self, page_widget=None):
        if page_widget:
            page_id = self.notebook.page_num(page_widget)
        else:
            page_id = int(self.notebook.get_current_page())
            page_widget = self.notebook.get_nth_page(page_id)
        if page_id != -1:
            page = None
            for i in range(len(self.pages)):
                if self.pages[i].widget == page_widget:
                    page = self.pages.pop(i)
                    break
            self.notebook.remove_page(page_id)

            next_page_id = -1
            to_pop = []
            for i in self.previous_pages:
                if self.previous_pages[i] == page_widget:
                    to_pop.append(i)
                if i.widget == page_widget:
                    if self.previous_pages[i]:
                        next_page_id = self.notebook.page_num(
                            self.previous_pages[i])
                    to_pop.append(i)
            to_pop.reverse()
            for i in to_pop:
                self.previous_pages.pop(i)

            if hasattr(page, 'destroy'):
                page.destroy()
            del page

            current_widget = self.notebook.get_nth_page(next_page_id)
            if current_widget:
                current_widget.props.visible = True
            self.notebook.set_current_page(next_page_id)
        if not self.pages and self.menu_screen:
            self.menu_screen.set_cursor()
        return self.notebook.get_current_page() != -1

    def get_page(self, page_id=None):
        if page_id is None:
            page_id = self.notebook.get_current_page()
        if page_id == -1:
            return None
        page_widget = self.notebook.get_nth_page(page_id)
        for page in self.pages:
            if page.widget == page_widget:
                return page
        return None

    def _sig_page_changt(self, notebook, page, page_num):
        self.last_page = self.current_page
        last_form = self.get_page(self.current_page)
        if last_form:
            for dialog in last_form.dialogs:
                dialog.hide()

        self.current_page = self.notebook.get_current_page()
        current_form = self.get_page(self.current_page)

        def set_cursor():
            if self.current_page == self.notebook.get_current_page():
                current_form.set_cursor()
        # Using idle_add because the Gtk.TreeView grabs the focus at the
        # end of the event
        GLib.idle_add(set_cursor)
        for dialog in current_form.dialogs:
            dialog.show()

    def _open_url(self, url):
        loads = partial(json.loads, object_hook=object_hook)
        urlp = urlparse(url)
        if not urlp.scheme == 'gnuhealth':
            return
        urlp = urlparse('http' + url[6:])
        database, path = list(
            map(unquote, (urlp.path[1:].split('/', 1) + [''])[:2]))
        if not path:
            return
        type_, path = (path.split('/', 1) + [''])[:2]
        params = {}
        if urlp.params:
            try:
                params.update(dict(parse_qsl(urlp.params,
                              strict_parsing=True)))
            except ValueError:
                return

        def open_model(path):
            attributes = {}
            model, path = (path.split('/', 1) + [''])[:2]
            if not model:
                return
            attributes = {}
            try:
                attributes['view_ids'] = loads(params.get('views', '[]'))
                if 'limit' in params:
                    attributes['limit'] = loads(params.get('limit', 'null'))
                attributes['name'] = loads(params.get('name', '""'))
                attributes['search_value'] = loads(
                    params.get('search_value', '[]'))
                attributes['domain'] = loads(params.get('domain', '[]'))
                attributes['context'] = loads(params.get('context', '{}'))
                attributes['context_model'] = params.get('context_model')
                attributes['tab_domain'] = loads(
                    params.get('tab_domain', '[]'))
            except ValueError:
                return
            if path:
                try:
                    attributes['res_id'] = int(path)
                except ValueError:
                    return
                attributes['mode'] = ['form', 'tree']
            try:
                Window.create(model, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_wizard(wizard):
            attributes = {}
            if not wizard:
                return
            try:
                attributes['data'] = loads(params.get('data', '{}'))
                attributes['direct_print'] = loads(
                    params.get('direct_print', 'false'))
                attributes['name'] = loads(params.get('name', '""'))
                attributes['window'] = loads(params.get('window', 'false'))
                attributes['context'] = loads(params.get('context', '{}'))
            except ValueError:
                return
            try:
                Window.create_wizard(wizard, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_report(report):
            attributes = {}
            if not report:
                return
            try:
                attributes['data'] = loads(params.get('data', '{}'))
                attributes['direct_print'] = loads(
                    params.get('direct_print', 'false'))
                attributes['context'] = loads(params.get('context', '{}'))
            except ValueError:
                return
            try:
                Action.exec_report(report, **attributes)
            except Exception:
                # Prevent crashing the client
                return

        def open_url():
            try:
                url = loads(params.get('url', 'false'))
            except ValueError:
                return
            if url:
                webbrowser.open(url, new=2)

        if type_ == 'model':
            open_model(path)
        elif type_ == 'wizard':
            open_wizard(path)
        elif type_ == 'report':
            open_report(path)
        elif type_ == 'url':
            open_url()

        self.window.present()

    def open_url(self, url):
        def idle_open_url():
            self._open_url(url)
            return False
        GLib.idle_add(idle_open_url)

    def show_notification(self, title, msg, priority=1):
        notification = Gio.Notification.new(title)
        notification.set_body(msg)
        notification.set_priority(_PRIORITIES[priority])
        if sys.platform != 'win32' or GLib.glib_version >= (2, 57, 0):
            self.send_notification(None, notification)

    # GNU Health client
    def get_main_title(self):
        user = CONFIG['login.login']
        host = CONFIG['login.host']
        db = CONFIG['login.db']
        conn_info = f'{user}@{host}/{db}'
        if CONFIG['client.title']:
            res = f"{CONFIG['client.title']} - {conn_info}"
        else:
            res = conn_info
        return res

    # GNUHEALTH block
    # Initialize GNU Health environment
    def init_gnuhealth_env(self):
        # Init GNU Health CLI
        self.cli = None
        self.cli = Gtk.Entry()
        # Maximum of 64 chars
        self.cli.set_max_length(64)
        self.cli.set_placeholder_text(_("GNU Health Command"))
        # CLI colors
        self.cli.modify_base(Gtk.StateType.NORMAL, Gdk.Color(6, 69, 72))
        self.cli.modify_text(Gtk.StateType.NORMAL, Gdk.Color(0, 0, 0))

        # Init the GNU Health Status Bar
        self.statusbar = None
        self.footer = None
        self.ghheader = None
        self.ghheader_contents = None
        self.footer_contents = None
        self.statusbar = Gtk.Statusbar()
        self.context_id = self.statusbar.get_context_id("Statusbar")
        self.ghheader = Gtk.HBox()
        self.ghheader.set_size_request(200, -1)

        # Main footer
        self.ghfooter = Gtk.HBox()

        # Create initally a grid for the footer
        self.ghfooter_contents = Gtk.Grid()

        # Create initally a grid for the header
        self.ghheader_contents = Gtk.Grid()

        # Set GNU Health Footer
        self.set_ghfooter()

        # Include the side menu toggle
        side_menu = Gtk.Button.new()
        side_menu.set_image(
            common.IconFactory.get_image('gnuhealth-menu',
                                         Gtk.IconSize.BUTTON))
        side_menu.connect('clicked', self.menu_toggle)

        # End of side-menu toggle
        # Favorite entries
        favorite = Gtk.MenuButton.new()
        favorite.set_relief(Gtk.ReliefStyle.NONE)
        favorite.set_image(common.IconFactory.get_image(
            'gnuhealth-bookmarks', Gtk.IconSize.BUTTON))
        self.menu_favorite = Gtk.Menu.new()
        favorite.set_popup(self.menu_favorite)
        favorite.connect('clicked', self.favorite_set)

        self.set_global_search()

        # CLI position at top
        self.ghheader_contents.add(side_menu)
        self.ghheader_contents.attach_next_to(self.cli, side_menu,
                                              Gtk.PositionType.RIGHT, 1, 1)
        self.ghheader_contents.attach_next_to(favorite, self.cli,
                                              Gtk.PositionType.RIGHT, 1, 1)

        self.ghheader_contents.attach_next_to(
            self.global_search_entry, favorite, Gtk.PositionType.RIGHT, 1, 1)

        self.ghheader.pack_start(self.ghheader_contents, expand=True,
                                 fill=True, padding=10)
        self.vbox.pack_start(self.ghheader,
                             expand=False, fill=False, padding=10)

        self.vbox.reorder_child(self.ghheader, 1)

        self.ghheader.show_all()

    # Add GNU Health Command Line and Status Bar in footer
    def set_ghfooter(self):
        cli = self.cli
        statusbar = self.statusbar
        ghfooter_contents = self.ghfooter_contents

        ghfooter_contents.add(statusbar)

        self.ghfooter.pack_start(ghfooter_contents, expand=True, fill=True,
                                 padding=0)

        # Pack the footer table in main vbox
        self.vbox.pack_start(self.ghfooter, expand=False,
                             fill=False, padding=0)

        self.ghfooter.show_all()
        self.vbox.show_all()

        cli.connect('activate', self.activate_cli, self.context_id)

    # Parse the CLI arguments
    def activate_cli(self, widget, data):
        # Make the command case-insensitive
        command = widget.get_text().lower()
        if (command == 'sysinfo'):
            info = f"Request : {command} \n"
            client_info = '\n********* CLIENT INFORMATION *********\n\n'
            server_info = '\n********* SERVER INFORMATION *********\n\n'
            client_info = f"{client_info} {self.get_host_info()}\n"

            server_info = server_info + \
                RPCExecute('model', 'gnuhealth.command', command)

            info = info + client_info + server_info
            self.activity_log_entry(info, "info")
        else:
            if command:
                self.gnuhealth_cmd(command)

    # GNU Health system activity and status logger
    def activity_log_entry(self, msg, msg_type):
        time_stamp = time.strftime("%Y/%m/%d - %H:%M:%S")
        if (msg_type == "info"):
            mtype = "[INFO]"
        elif (msg_type == "info"):
            mtype = "[WARN]"
        else:
            mtype = "[ERROR]"

        log_entry = time_stamp + "  " + mtype + ": " + msg + "\n"

        next_line = Activity.textbuffer.get_end_iter()

        Activity.textbuffer.insert(next_line, log_entry)

    # Reset and clean GNU Health environment
    def reset_gnuhealth_env(self):
        if self.cli:
            self.cli.destroy()

        if self.statusbar:
            self.statusbar.remove_all(self.context_id)

        if self.footer_contents:
            self.footer_contents.destroy()

        if self.footer:
            self.footer.destroy()

    def get_host_info(self):
        info = ""
        os_header = "\n-- Operating System / Distribution --\n"
        uname = platform.uname()
        client_version = f"GNU Health GTK Client version: {__version__}"
        pversion = f"Python version : {platform.python_version()}"
        with open('/etc/os-release') as f:
            os_version = f.readlines()
        # Get OS version and related info.
        os_info = ''
        with open('/etc/os-release') as f:
            os_release = f.readlines()
            for line in os_release:
                os_info = os_info + str(line)
        # Get relevant environment variables

        info = f"{info} {pversion}\n {client_version}\n" \
            f"{os_header} {os_version} {os_info}\n" \
            f"Platform / Kernel Info: {str(uname)}"

        return info

    def gnuhealth_cmd(self, command):

        cmd = command.split()[0]
        args = command.split()[1:]
        domain_name = None
        search_string = '%'

        res = RPCExecute('model', 'gnuhealth.command', 'search_read',
                         [('name', '=', cmd)], 0, 1, None,
                         ['name', 'model', 'label', 'domain'])

        if (res):
            res = res[0]
            if (res['domain']):
                domain_name = ast.literal_eval(res['domain'])
            model_name = res['model']
            label = res['label']
            if args:
                arg1 = args.pop()
                search_string = "%" + arg1 + "%"

            Window.create(
                model_name,
                mode=['tree', 'form'],
                name=label,
                domain=domain_name,
                limit=CONFIG['client.limit'],
                search_value=[('rec_name', 'ilike', search_string)]
            )

        else:
            common.message(_('Command not found.'))

    # Toggle GNU Health Activity window
    def activity_toggle(self):
        if Activity().activity_window.get_visible():
            Activity().activity_window.hide()
        else:
            Activity().activity_window.show_all()
