# icon_picker_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, GObject
from .constants import PROJECT_ICONS


@Gtk.Template(resource_path='/cz/bugsy/roster/icon-picker-dialog.ui')
class IconPickerDialog(Adw.Dialog):
    """Dialog for selecting a project icon."""

    __gtype_name__ = 'IconPickerDialog'

    icon_flowbox = Gtk.Template.Child()

    __gsignals__ = {
        'icon-selected': (GObject.SIGNAL_RUN_FIRST, None, (str,)),
    }

    def __init__(self, current_icon=None):
        super().__init__()
        self.current_icon = current_icon
        self._populate_icons()

    def _populate_icons(self):
        """Populate the flowbox with icon buttons."""
        for icon_name in PROJECT_ICONS:
            button = Gtk.Button()
            button.set_icon_name(icon_name)
            button.set_tooltip_text(icon_name)
            button.add_css_class("flat")
            button.set_size_request(48, 48)

            # Create icon image with larger size
            icon = Gtk.Image.new_from_icon_name(icon_name)
            icon.set_icon_size(Gtk.IconSize.LARGE)
            button.set_child(icon)

            # Store icon name as data
            button.icon_name = icon_name

            # Highlight current icon
            if icon_name == self.current_icon:
                button.add_css_class("suggested-action")

            # Connect button click directly
            button.connect('clicked', self.on_icon_button_clicked)

            self.icon_flowbox.append(button)

    def on_icon_button_clicked(self, button):
        """Handle icon button click."""
        if hasattr(button, 'icon_name'):
            self.emit('icon-selected', button.icon_name)
            self.close()

    @Gtk.Template.Callback()
    def on_icon_selected(self, flowbox, child):
        """Handle icon selection (unused - kept for compatibility)."""
        pass
