# main.py
#
# Copyright 2025 Pavel Baksy
#
# 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 <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import sys
import gi

gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')

from gi.repository import Gtk, Gio, Adw
from .window import RosterWindow
from .preferences_dialog import PreferencesDialog
from . import constants


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

    def __init__(self, version='0.0.0'):
        super().__init__(application_id='cz.bugsy.roster',
                         flags=Gio.ApplicationFlags.DEFAULT_FLAGS,
                         resource_base_path='/cz/bugsy/roster')
        self.version = version
        self.create_action('quit', lambda *_: self.quit(), ['<control>q'])
        self.create_action('about', self.on_about_action)
        self.create_action('preferences', self.on_preferences_action)
        self.create_action('shortcuts', self.on_shortcuts_action, ['<control>question'])

    def do_activate(self):
        """Called when the application is activated.

        We raise the application's main window, creating it if
        necessary.
        """
        win = self.props.active_window
        if not win:
            win = RosterWindow(application=self)
        win.present()

    def on_about_action(self, *args):
        """Callback for the app.about action."""
        about = Adw.AboutDialog(application_name='Roster',
                                application_icon='cz.bugsy.roster',
                                developer_name='Pavel Baksy',
                                version=self.version,
                                developers=['Pavel Baksy'],
                                copyright='© 2025 Pavel Baksy',
                                comments='HTTP client for testing APIs')
        about.set_website('https://git.bugsy.cz/beval/roster')
        about.set_issue_url('https://git.bugsy.cz/beval/roster/issues')
        about.set_license_type(Gtk.License.GPL_3_0)

        # Add legal notice about icon licensing
        about.add_legal_section(
            'Application Icons',
            None,
            Gtk.License.CUSTOM,
            'Application icons are licensed under CC-BY-SA-3.0\n'
            'https://creativecommons.org/licenses/by-sa/3.0/'
        )

        # Translators: Replace "translator-credits" with your name/username, and optionally an email or URL.
        about.set_translator_credits(_('translator-credits'))
        about.present(self.props.active_window)

    def on_preferences_action(self, widget, _):
        """Callback for the app.preferences action."""
        window = self.props.active_window
        preferences = PreferencesDialog(history_manager=window.history_manager)
        preferences.set_transient_for(window)
        preferences.connect('history-cleared', lambda d: window._load_history())
        preferences.present()

    def on_shortcuts_action(self, widget, _):
        """Callback for the app.shortcuts action."""
        builder = Gtk.Builder.new_from_resource('/cz/bugsy/roster/shortcuts-dialog.ui')
        shortcuts_window = builder.get_object('shortcuts_dialog')
        shortcuts_window.set_transient_for(self.props.active_window)
        shortcuts_window.present()

    def create_action(self, name, callback, shortcuts=None):
        """Add an application action.

        Args:
            name: the name of the action
            callback: the function to be called when the action is
              activated
            shortcuts: an optional list of accelerators
        """
        action = Gio.SimpleAction.new(name, None)
        action.connect("activate", callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f"app.{name}", shortcuts)


def main(version):
    """The application's entry point."""
    # Set the version constant for use throughout the application
    constants.VERSION = version
    app = RosterApplication(version=version)
    return app.run(sys.argv)
