# main.py
#
# Copyright 2020-2024 Fabio Comuni, et al.
#
# 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 sys
from gettext import gettext as _

import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
gi.require_version("Notify", "0.7")

from gi.repository import Gtk, Gdk, Gio, GLib, GObject
from gi.repository import Adw
from gi.repository import Notify

from . import local
from .config import APP_NAME, APP_ID, APP_VERSION  # type:ignore # config is generated at compile time
from .preferences import PreferencesWindow
from .openwindow import OpenWindow
from .mainwindow import MainWindow


class Application(Gtk.Application):
    @GObject.Signal
    def tick(self):
        """Event fired every minute

        Used to check for notifications to send and to update events row background
        """
        pass

    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()

        # resource icons in icon theme path
        icon_theme = Gtk.IconTheme.get_for_display(display)
        icon_theme.add_resource_path("/net/kirgroup/confy/icons")

        # custom css
        css_provider = Gtk.CssProvider()
        css_provider.load_from_resource("/net/kirgroup/confy/confy.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)
        self.connect("shutdown", self.on_shutdown)
        return super().run(argv)

    def on_startup(self, *_):
        Adw.init()
        Notify.init(APP_NAME)
        local.init(APP_ID)

        self._add_action('quit', None, ["<Primary>q",], lambda *args: self.quit())
        self._add_action('shortcuts', None, ["<Primary>question"], self.show_shortcuts)
        self._add_action('preferences', None, ["<Primary>comma",], self.show_preferences)
        self._add_action('about', None, None, self.show_about)

        GLib.timeout_add_seconds(30, self._do_tick)

    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 _do_tick(self):
        self.emit("tick")
        return True

    def open_conf(self, conf):
        win = self.props.active_window
        if isinstance(win, OpenWindow):
            win.close()
            win = self.props.active_window
        win.load_conf(conf)
        win.present()

    # def start_window(self):
    #    a_win = self.props.active_window
    #    win = OpenWindow(application=self)
    #    if isinstance(a_win, MainWindow):
    #        win.connect("show", lambda *_: a_win.destroy())
    #    win.present()

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

    def on_shutdown(self, *_):
        local.close()

    def show_shortcuts(self, *_):
        b = Gtk.Builder.new_from_resource("/net/kirgroup/confy/shortcuts.ui")
        w = b.get_object("shortcuts-win")
        w.set_transient_for(self.props.active_window)
        w.props.view_name = None
        w.show()

    def show_preferences(self, *args):
        pref = PreferencesWindow(transient_for=self.props.active_window)
        pref.show()

    def show_about(self, *args):
        Adw.AboutWindow(
            application_name=APP_NAME,
            application_icon=APP_ID,
            version=APP_VERSION,
            copyright="© 2020-2023 Fabio Comuni, et al.",
            website="https://confy.kirgroup.net/",
            issue_url="https://todo.sr.ht/~fabrixxm/confy",
            developers=["Fabio Comuni", "Evangelos Ribeiro Tzaras", "Sebastian Crane"],
            # 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!
            translator_credits=_("translator-credits"),
            comments=_("Conference schedules viewer"),
            license_type=Gtk.License.GPL_3_0
        ).show()


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