# SPDX-FileCopyrightText: 2024 Luca Weiss
# SPDX-License-Identifier: GPL-3.0-only

import sys
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Adw
from gi.repository import Gtk, Gdk, Gio, GLib

from .config import APP_NAME, APP_ID, APP_VERSION
from .mainwindow import MainWindow


class Application(Gtk.Application):
    def __init__(self):
        super().__init__(application_id=APP_ID,
                         flags=Gio.ApplicationFlags.FLAGS_NONE)
        GLib.set_application_name(APP_NAME)
        GLib.set_prgname(APP_ID)

        display = Gdk.Display.get_default()

        # custom css
        css_provider = Gtk.CssProvider()
        css_provider.load_from_resource("/eu/lucaweiss/lpa-gtk/lpa-gtk.css")
        Gtk.StyleContext.add_provider_for_display(
            display,
            css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

    def run(self, argv):
        self.connect("startup", self.on_startup)
        self.connect("activate", self.on_activate)
        return super().run(argv)

    def on_startup(self, *_):
        Adw.init()

        self._add_action('about', None, None, self.show_about)

    def _add_action(self, name, parameter_type, accels, activate_cbk):
        action = Gio.SimpleAction.new(name, parameter_type)
        action.connect("activate", activate_cbk)
        self.add_action(action)
        if accels is not None:
            self.set_accels_for_action(F"app.{name}", accels)
        return action

    def on_activate(self, *_):
        win = self.props.active_window
        if not win:
            win = MainWindow(application=self)
        self.win = win
        win.present()

    def show_about(self, *args):
        about_dialog = Adw.AboutDialog.new_from_appdata("/eu/lucaweiss/lpa-gtk/appdata/info.xml",
                                                        release_notes_version=APP_VERSION)
        # Translators: about dialog text; this string should be replaced by a
        # text crediting yourselves and your translation team, or should be
        # left empty. Do not translate literally!
        about_dialog.set_translator_credits(_("translator_credits"))
        about_dialog.set_copyright("© 2024 Luca Weiss")
        about_dialog.present(self.win)


def main():
    app = Application()
    return app.run(sys.argv)
