# SPDX-FileCopyrightText: 2022 Chris Heywood
#
# SPDX-License-Identifier: GPL-3.0-or-later

from gi.repository import Gio, Gtk

from iotas.config_manager import ConfigManager


@Gtk.Template(resource_path="/org/gnome/World/Iotas/ui/theme_selector.ui")
class ThemeSelector(Gtk.Box):
    __gtype_name__ = "ThemeSelector"

    _follow: Gtk.CheckButton = Gtk.Template.Child()
    _light: Gtk.CheckButton = Gtk.Template.Child()
    _dark: Gtk.CheckButton = Gtk.Template.Child()

    def __init__(self) -> None:
        super().__init__()
        self.__config_manager = ConfigManager.get_default()
        self.__populate()
        self.__config_manager.connect_changed(ConfigManager.STYLE, self.__populate)

    @Gtk.Template.Callback()
    def _on_option_selected(self, _widget: Gtk.CheckButton) -> None:
        name = None
        if self._follow.get_active():
            name = "follow"
        elif self._light.get_active():
            name = "light"
        elif self._dark.get_active():
            name = "dark"
        # Name can be null when checkbutton is unchecked for radio group. A positive check will
        # follow.
        if name and self.__config_manager.style != name:
            self.__config_manager.style = name
            app = Gio.Application.get_default()
            app.apply_style()

    def __populate(self) -> None:
        style = self.__config_manager.style
        if style == "follow":
            self._follow.set_active(True)
        elif style == "light":
            self._light.set_active(True)
        else:
            self._dark.set_active(True)
