# Copyright (c) 2020-2022 Jan-Michael Brummer <jan.brummer@tabos.org>
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

import logging
from gi.repository import Adw, Gio, GLib, Gtk

from saldo.widgets.mod import load_widgets
from saldo.window import Window
from saldo import const


class Application(Adw.Application):
    application_id = const.APP_ID
    settings = Gio.Settings.new(application_id)

    def __init__(self, application_id):
        super().__init__(
            application_id=application_id,
            flags=Gio.ApplicationFlags.FLAGS_NONE,
            resource_base_path="/org/tabos/saldo",
        )

        self._window = None
        self.start_hidden = False

        # debug level logging option
        self.add_main_option(
            "debug",
            ord("d"),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            "Enable debug logging",
            None,
        )
        self.add_main_option(
            "hidden",
            ord("h"),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            "Start window hidden",
            None,
        )

    def add_global_accelerators(self):
        self.set_accels_for_action("window.close", ["<Control>w"])

        self.set_accels_for_action("win.lock", ["<Control>l"])
        self.set_accels_for_action("win.refresh", ["<Control>r"])
        self.set_accels_for_action("win.settings", ["<Control>comma"])
        self.set_accels_for_action("win.transfer", ["<Control>t"])

        self.set_accels_for_action("app.quit", ["<Control>q"])

    def do_handle_local_options(  # pylint: disable=arguments-differ
        self, options: GLib.VariantDict
    ) -> int:
        """
        :returns int: If you have handled your options and want to exit
            the process, return a non-negative option, 0 for success, and
            a positive value for failure. To continue, return -1 to let
            the default option processing continue.
        """
        #  convert GVariantDict -> GVariant -> dict
        options = options.end().unpack()

        # set up logging depending on the verbosity level
        loglevel = logging.INFO
        if "debug" in options:
            loglevel = logging.DEBUG

        if "hidden" in options and self._window is None:
            self.start_hidden = True

        logging.basicConfig(
            format="%(asctime)s | %(levelname)s | %(message)s",
            datefmt="%d-%m-%y %H:%M:%S",
            level=loglevel,
        )

        return -1

    def do_startup(self):  # pylint: disable=arguments-differ
        Adw.Application.do_startup(self)

        self.setup_actions()
        self.add_global_accelerators()

        load_widgets()

    def do_activate(self):  # pylint: disable=arguments-differ
        self._window = Gtk.Application.get_active_window(self)

        if not self._window:
            self._window = Window(application=self)

        if self.start_hidden:
            self._window.hide()
            self.start_hidden = False
        else:
            self._window.present()

    def setup_actions(self):
        quit_action = Gio.SimpleAction.new("quit", None)
        quit_action.connect("activate", self.on_quit_action)
        self.add_action(quit_action)

    def on_quit_action(self, _action: Gio.Action, _param: GLib.Variant) -> None:
        for window in self.get_windows():
            window.destroy()
