# value_combo_row.py
#
# Copyright 2025 Mitchell Winkelman (Heliguy)
#
# 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/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later


from gi.repository import GObject, Gtk

from refine.widgets.base import InvalidSettingError
from refine.widgets.combo_row import ComboRow

MINIMUM_CHILDREN = 2


@Gtk.Template.from_resource("/page/tesk/Refine/widgets/value-combo-row.ui")
class ValueComboRow(ComboRow):
    """An `Adw.ComboRow` implementing the properties needed to work with enumerated properties in `Gio.Settings`."""

    __gtype_name__ = "ValueComboRow"

    revert_button = Gtk.Template.Child()
    revealer = Gtk.Template.Child()

    title_case = GObject.Property(type=bool, default=False)
    omit_hyphens = GObject.Property(type=bool, default=False)
    omit_words = GObject.Property(type=str)

    def do_setup(self) -> None:
        enum_tuple: tuple[str, list[str]] = (
            self.schema.get_key(self.key).get_range().unpack()
        )
        if len(enum_tuple) < MINIMUM_CHILDREN or enum_tuple[0] != "enum":
            raise InvalidSettingError

        self.original_list = enum_tuple[1]

        self.transformed_list = self.original_list

        if self.omit_words:
            for word in self.omit_words.split():
                self.transformed_list = [
                    string.replace(word.lower(), "") for string in self.transformed_list
                ]

        if self.omit_hyphens:
            self.transformed_list = [
                string.replace("-", " ") for string in self.transformed_list
            ]

        if self.title_case:
            self.transformed_list = [string.title() for string in self.transformed_list]

        self.transformed_list = [string.strip() for string in self.transformed_list]

        combined_lists = sorted(
            zip(self.transformed_list, self.original_list, strict=False)
        )
        self.transformed_list = [string[0] for string in combined_lists]
        self.original_list = [string[1] for string in combined_lists]

        model = Gtk.StringList.new(self.transformed_list)
        string: str = self.settings.get_string(self.key)
        self.set_model(model)
        self.set_selected(self.original_list.index(string))

        self.set_is_default(self.key)
        self.connect("notify::selected", self.selected_callback)
        super().do_setup()
