# flags_switch_row.py
#
# Copyright 2024 Hari Rana (TheEvilSkeleton)
#
# 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

import contextlib
from typing import Any, cast

from gi.repository import Gtk

from refine.widgets.base import InvalidSettingError
from refine.widgets.string_row import StringRow


@Gtk.Template.from_resource("/page/tesk/Refine/widgets/flags-switch-row.ui")
class FlagsSwitchRow(StringRow):
    """A `ActionRow` to enable or disable a feature from a string list."""

    __gtype_name__ = "FlagsSwitchRow"

    def get_string(self) -> list[str]:
        """Retrieve list from key."""
        return self.settings.get_strv(self.key)

    def active_set(self, *_args: Any) -> None:
        """Set whether @self is in its “on” or “off” position."""
        flags = self.get_string()

        value = cast("str", self.value)
        if self.active:
            flags.append(value)
        else:
            with contextlib.suppress(ValueError):
                flags.remove(value)

        flags = list(set(flags))

        self.settings.set_strv(self.key, flags)
        self.value_set(flags)
        self.do_update()

    def do_update(self) -> None:
        super().do_update()
        schema_key = self.schema.get_key(self.key)

        try:
            key_range = schema_key.get_range()[1]

            if self.value not in key_range:
                raise InvalidSettingError
        except (IndexError, TypeError) as error:
            raise InvalidSettingError from error
