import Gio from 'gi://Gio';

import * as Main from 'resource:///org/gnome/shell/ui/main.js';

const APPEARANCE_CONSTS = {
    logPrefix: 'Appearance Feature',
    interfaceSchema: 'org.gnome.desktop.interface',
    lightGtkTheme: 'adw-gtk3',
    darkGtkTheme: 'adw-gtk3-dark',
    darkPanelClass: 'still-dark-panel',
    lightPanelClass: 'still-light-panel',
};

export default class AppearanceFeature {
    enable() {
        this._interfaceSettings = new Gio.Settings({ schema_id: APPEARANCE_CONSTS.interfaceSchema });
        this._colorSchemeChangedId = this._interfaceSettings.connect('changed::color-scheme', () => {
            this._syncAppearance();
        });
        this._syncAppearance();
    }

    _syncAppearance() {
        this._syncLegacyGtkTheme();
        this._syncPanelTheme();
    }

    _isDarkColorScheme(colorScheme) {
        return colorScheme !== 'prefer-light';
    }

    _syncLegacyGtkTheme() {
        if (!this._interfaceSettings)
            return;

        let colorScheme;
        try {
            colorScheme = this._interfaceSettings.get_string('color-scheme');
        } catch (e) {
            log(`${APPEARANCE_CONSTS.logPrefix}: Failed reading color-scheme: ${e}`);
            return;
        }

        const targetTheme = this._isDarkColorScheme(colorScheme)
            ? APPEARANCE_CONSTS.darkGtkTheme
            : APPEARANCE_CONSTS.lightGtkTheme;

        try {
            if (this._interfaceSettings.get_string('gtk-theme') !== targetTheme)
                this._interfaceSettings.set_string('gtk-theme', targetTheme);
        } catch (e) {
            log(`${APPEARANCE_CONSTS.logPrefix}: Failed setting gtk-theme to ${targetTheme}: ${e}`);
        }
    }

    _syncPanelTheme() {
        if (!this._interfaceSettings || !Main.panel)
            return;

        let colorScheme;
        try {
            colorScheme = this._interfaceSettings.get_string('color-scheme');
        } catch (e) {
            log(`${APPEARANCE_CONSTS.logPrefix}: Failed reading color-scheme for panel: ${e}`);
            return;
        }

        const useDarkPanel = this._isDarkColorScheme(colorScheme);

        Main.panel.remove_style_class_name(APPEARANCE_CONSTS.darkPanelClass);
        Main.panel.remove_style_class_name(APPEARANCE_CONSTS.lightPanelClass);
        Main.panel.add_style_class_name(
            useDarkPanel ? APPEARANCE_CONSTS.darkPanelClass : APPEARANCE_CONSTS.lightPanelClass
        );
    }

    disable() {
        if (Main.panel) {
            Main.panel.remove_style_class_name(APPEARANCE_CONSTS.darkPanelClass);
            Main.panel.remove_style_class_name(APPEARANCE_CONSTS.lightPanelClass);
        }

        if (this._interfaceSettings && this._colorSchemeChangedId) {
            this._interfaceSettings.disconnect(this._colorSchemeChangedId);
            this._colorSchemeChangedId = null;
        }
        this._interfaceSettings = null;
    }
}
