# export_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, Gdk, GLib
import logging

logger = logging.getLogger(__name__)


@Gtk.Template(resource_path='/cz/bugsy/roster/export-dialog.ui')
class ExportDialog(Adw.Dialog):
    """Dialog for exporting HTTP requests in various formats."""

    __gtype_name__ = 'ExportDialog'

    export_textview = Gtk.Template.Child()
    copy_button = Gtk.Template.Child()

    def __init__(self, request, **kwargs):
        """
        Initialize export dialog.

        Args:
            request: HttpRequest to export (should have variables substituted)
        """
        super().__init__(**kwargs)
        self.request = request
        self._populate_export()

    def _populate_export(self):
        """Generate and display the export content."""
        try:
            # Get cURL exporter
            from .exporters import ExporterRegistry
            exporter = ExporterRegistry.get_exporter('curl')

            # Generate cURL command
            curl_command = exporter.export(self.request)

            # Display in textview
            buffer = self.export_textview.get_buffer()
            buffer.set_text(curl_command)

        except Exception as e:
            logger.error(f"Export generation failed: {e}")
            buffer = self.export_textview.get_buffer()
            buffer.set_text(f"Error generating export: {str(e)}")

    @Gtk.Template.Callback()
    def on_copy_clicked(self, button):
        """Copy export content to clipboard."""
        # Get text from buffer
        buffer = self.export_textview.get_buffer()
        start = buffer.get_start_iter()
        end = buffer.get_end_iter()
        text = buffer.get_text(start, end, False)

        # Copy to clipboard using Gdk.Clipboard API
        display = Gdk.Display.get_default()
        clipboard = display.get_clipboard()
        clipboard.set(text)

        # Visual feedback: temporarily change button label
        original_label = button.get_label()
        button.set_label("Copied!")

        # Reset after 2 seconds
        def reset_label():
            button.set_label(original_label)
            return False  # Don't repeat

        GLib.timeout_add(2000, reset_label)

        logger.debug("Export copied to clipboard")
