import Gio from 'gi://Gio';
import St from 'gi://St';
import GLib from 'gi://GLib';
import * as Log from '../modules/log.js';

export class File {
    static DBus(name, path = '') {
        const decoder = new TextDecoder();
        const file = `${path}/resources/dbus/${name}.xml`;

        try {
            const [ok, bytes] = GLib.file_get_contents(file);
            if (!ok)
                Log.warn(`Couldn't read contents of "${file}"`);
            return ok ? decoder.decode(bytes) : undefined;
        }
        catch (e) {
            Log.error(`Failed to load "${file}"`, e);
        }
    }
}

export class Icon {
    static getByName(name) {
        const iconTheme = new St.IconTheme();
        iconTheme.prepend_search_path(SGFXGEX_PATH + '/resources/icons');

        try {
            if (iconTheme.has_icon(name)) {
                return new Gio.FileIcon({
                    file: Gio.File.new_for_path(iconTheme.choose_icon([name], -1, 2).get_filename()),
                });
            }
            else {
                Log.error(`icon not found locally: ${name} - try to load themed..`);
            }
        }
        catch (ex) {
            Log.error('icon loading error', ex);
        }
        return new Gio.ThemedIcon({ name: name });
    }
}
