from collections.abc import Callable, Sequence
from gettext import gettext as _
from typing import Any, override

from gi.repository import Adw, Gio

from morphosis import APP_ID, PREFIX, VERSION

from .ui.window import Window


class Application(Adw.Application):
    """The main application."""

    def __init__(self) -> None:
        super().__init__(application_id=APP_ID)

        self._create_action("quit", lambda *_: self.quit(), ("<Control>q",))
        self._create_action("about", lambda *_: self._present_about_dialog())

    @override
    def do_activate(self) -> None:
        window = self.props.active_window or Window(application=self)
        window.present()

    def _present_about_dialog(self) -> None:
        dialog = Adw.AboutDialog.new_from_appdata(
            f"{PREFIX}/{APP_ID}.metainfo.xml", VERSION
        )
        # Translators: Replace "translator-credits" with your name/username,
        # and optionally a URL or an email in <me@example.org> format.
        dialog.props.translator_credits = _("translator-credits")
        dialog.props.developers = [
            "Jamie Gravendeel https://jamie.garden",
            "kramo https://kramo.page",
        ]
        dialog.props.artists = [
            "kramo https://kramo.page",
            "Jakub Steiner https://jimmac.eu",
            "Tobias Bernard https://tobiasbernard.com",
        ]
        dialog.props.copyright = "© 2024 Jamie Gravendeel"
        dialog.present(self.props.active_window)

    def _create_action(
        self,
        name: str,
        callback: Callable[..., Any],
        shortcuts: Sequence[str] | None = None,
    ) -> None:
        action = Gio.SimpleAction.new(name)
        action.connect("activate", callback)
        self.add_action(action)

        if shortcuts:
            self.set_accels_for_action(f"app.{name}", shortcuts)
