import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
import os
import subprocess

class ThemeChangerWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="DEKUVE Themes")
        self.set_default_size(300, 400)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        vbox.set_margin_top(0)  # Отступ сверху
        vbox.set_margin_bottom(25)  # Отступ снизу
        vbox.set_margin_start(25)  # Отступ слева
        vbox.set_margin_end(25)  # Отступ справа
        self.add(vbox)

        image = Gtk.Image.new_from_file("/opt/dekuve-p/dekuve-themes.svg")
        vbox.pack_start(image, False, False, 10)  # Отступ 10 пикселей сверху

        label = Gtk.Label("Select a theme:")
        vbox.pack_start(label, False, False, 0)

        self.theme_combobox = Gtk.ComboBoxText()
        vbox.pack_start(self.theme_combobox, False, False, 0)

        label_icons = Gtk.Label("Select an icon theme:")
        vbox.pack_start(label_icons, False, False, 0)

        self.icon_theme_combobox = Gtk.ComboBoxText()
        vbox.pack_start(self.icon_theme_combobox, False, False, 0)

        apply_button = Gtk.Button(label="Apply Theme")
        apply_button.connect("clicked", self.apply_button_clicked)
        vbox.pack_start(apply_button, False, False, 0)

        self.populate_theme_list()

    def populate_theme_list(self):
        themes_dir = os.path.expanduser("~/.themes")
        if os.path.exists(themes_dir):
            themes = [name for name in os.listdir(themes_dir) if os.path.isdir(os.path.join(themes_dir, name))]
            self.theme_combobox.remove_all()
            for theme in themes:
                self.theme_combobox.append_text(theme)
            self.theme_combobox.set_active(0)  # Выбираем первую тему по умолчанию

        icons_dir = os.path.expanduser("~/.icons")
        if os.path.exists(icons_dir):
            icon_themes = [name for name in os.listdir(icons_dir) if os.path.isdir(os.path.join(icons_dir, name))]
            self.icon_theme_combobox.remove_all()
            for icon_theme in icon_themes:
                self.icon_theme_combobox.append_text(icon_theme)
            self.icon_theme_combobox.set_active(0)  # Выбираем первую тему иконок по умолчанию

    def apply_button_clicked(self, button):
        active_theme = self.theme_combobox.get_active_text()
        active_icon_theme = self.icon_theme_combobox.get_active_text()
        if active_theme:
            try:
                # Используем xfconf для применения темы в XFWM4 и XFCE
                subprocess.run(["xfconf-query", "-c", "xfwm4", "-p", "/general/theme", "-s", active_theme])
                subprocess.run(["xfconf-query", "-c", "xsettings", "-p", "/Net/ThemeName", "-s", active_theme])
                subprocess.run(["xfconf-query", "-c", "xsettings", "-p", "/Net/IconThemeName", "-s", active_icon_theme])
                print(f"XFWM4 and XFCE theme '{active_theme}' and icon theme '{active_icon_theme}' applied successfully.")

                # Устанавливаем глобальную переменную окружения для применения темы и иконок в Flatpak-приложениях
                os.environ["GSETTINGS_SCHEMA_DIR"] = "/usr/share/glib-2.0/schemas"
                subprocess.run(["flatpak", "override", "--user", "--env=GTK_THEME=" + active_theme, "--env=ICON_THEME=" + active_icon_theme])

                print(f"Flatpak theme '{active_theme}' and icon theme '{active_icon_theme}' applied successfully.")
            except Exception as e:
                print(f"Error applying theme: {e}")

win = ThemeChangerWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

