# string_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

from typing import Any, cast

from gi.repository import GObject

from refine.logger import logger
from refine.widgets.toggle_row import ToggleRow


class StringRow(ToggleRow):
    """A `ToggleRow` adding the base properties and functionality to manipulate strings and string lists."""

    __gtype_name__ = "StringRow"

    value = GObject.Property(type=str)

    def _settings_changed(self, *_args: Any) -> None:
        flag = self.get_string()
        is_setting_active = cast("str", self.value) in flag

        if self.active != is_setting_active:
            self.emit("inconsistent")

    def _inconsistent_set(self, *_args: Any) -> None:
        self.handler_block_by_func(self.active_set)  # type: ignore [no-untyped-call]
        flag = self.get_string()
        self.active = cast("str", self.value) in flag
        self.value_set(flag)
        self.handler_unblock_by_func(self.active_set)  # type: ignore [no-untyped-call]

    def get_string(self) -> str | list[str]:
        """String or list getter virtual method."""
        raise NotImplementedError

    def active_set(self, *_args: Any) -> None:
        """Active setter virtual method."""
        raise NotImplementedError

    def do_setup(self) -> None:
        super().do_setup()
        self.active = cast("str", self.value) in self.get_string()
        self.connect("notify::active", self.active_set)
        self.connect("inconsistent", self._inconsistent_set)
        self.settings.connect("changed", self._settings_changed)

    @GObject.Signal
    def inconsistent(self) -> None:
        """Log inconsistency signal."""
        logger.info(f"{self.__class__.__name__}::inconsistent signal emitted")
