# preferences_dialog.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

from gi.repository import Adw, Gtk, Gio, GObject


@Gtk.Template(resource_path='/cz/bugsy/roster/preferences-dialog.ui')
class PreferencesDialog(Adw.PreferencesWindow):
    __gtype_name__ = 'PreferencesDialog'

    tls_verification_row = Gtk.Template.Child()
    timeout_row = Gtk.Template.Child()
    clear_history_button = Gtk.Template.Child()

    __gsignals__ = {
        'history-cleared': (GObject.SIGNAL_RUN_FIRST, None, ())
    }

    def __init__(self, history_manager=None, **kwargs):
        super().__init__(**kwargs)

        self.history_manager = history_manager

        # Get settings
        self.settings = Gio.Settings.new('cz.bugsy.roster')

        # Bind settings to UI
        self.settings.bind(
            'force-tls-verification',
            self.tls_verification_row,
            'active',
            Gio.SettingsBindFlags.DEFAULT
        )

        self.settings.bind(
            'request-timeout',
            self.timeout_row,
            'value',
            Gio.SettingsBindFlags.DEFAULT
        )

    @Gtk.Template.Callback()
    def on_clear_history_clicked(self, button):
        """Clear all history after confirmation."""
        if not self.history_manager:
            return

        # Create confirmation dialog
        dialog = Adw.AlertDialog.new(
            "Clear All History?",
            "This will permanently delete all saved request and response history. This action cannot be undone."
        )
        dialog.add_response("cancel", "Cancel")
        dialog.add_response("clear", "Clear History")
        dialog.set_response_appearance("clear", Adw.ResponseAppearance.DESTRUCTIVE)
        dialog.set_default_response("cancel")
        dialog.set_close_response("cancel")

        def on_response(dialog, response):
            if response == "clear":
                # Clear the history
                self.history_manager.clear_history()
                # Notify the main window to refresh
                self.emit('history-cleared')

        dialog.connect("response", on_response)
        dialog.present(self)
