# adjustment.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 GLib, GObject, Gio, Gtk

from refine.logger import logger
from refine.widgets.base import BaseInterface
from refine.widgets.reset_button import ResetButton


class Adjustment(Gtk.Adjustment, BaseInterface):
    """
    Derivative of `Gtk.Adjustment` implementing the properties needed to work with `Gio.Settings`.

    This widget is meant to be used in conjunction with widgets relying on `Gtk.Adjustment`.
    """

    __gtype_name__ = "Adjustment"

    settings = cast("Gio.Settings", GObject.Property(type=Gio.Settings))
    schema_id = cast("str", GObject.Property(type=str))
    schema = cast("Gio.SettingsSchema", GObject.Property(type=Gio.SettingsSchema))
    key = cast("str", GObject.Property(type=str))
    is_valid_setting = cast("bool", GObject.Property(type=bool, default=False))

    revealer = GObject.Property(type=Gtk.Revealer)
    reset_button = GObject.Property(type=ResetButton)
    sensitive = GObject.Property(type=bool, default=True)
    restart_required = GObject.Property(type=bool, default=False)

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(**kwargs)
        BaseInterface.__init__(self, **kwargs)

    def _reset_button_clicked(self, *_args: Any) -> None:
        logger.debug("Revert button pressed")
        self.settings.reset(self.key)
        self.set_value(self.settings.get_value(self.key).unpack())
        self.do_update()

    def _value_changed(self, _adjustment: Gtk.Adjustment, *_args: Any) -> None:
        value_type = self.schema.get_key(self.key).get_value_type()
        format_string = value_type.dup_string()
        variant = GLib.Variant(format_string, self.get_value())

        self.settings.set_value(self.key, variant)
        self.value_set(int(self.get_value()))
        self.do_update()

    def do_setup(self) -> None:
        type Range = tuple[Any, tuple[int, int]]

        schema_key = self.schema.get_key(self.key)
        variant = cast("Range", schema_key.get_range())
        range = variant[1]

        self.set_lower(range[0])
        self.set_upper(range[1])
        self.set_value(self.settings.get_value(self.key).unpack())
        self.do_update()

        self.reset_button.connect("clicked", self._reset_button_clicked)
        self.connect("value-changed", self._value_changed)
        BaseInterface.set_up_separator_revealer(self.revealer, self.reset_button)

    def do_update(self) -> None:
        default_value = cast("GLib.Variant", self.settings.get_default_value(self.key))
        default_int = default_value.unpack()
        value = int(self.get_value())

        self.reset_button.set_sensitive(value != default_int)

    def value_set(self, value: Any) -> None:
        """Log key-value pair."""
        logger.debug(f"Set key “{self.key}” to “{value}”")
