/* activities.js
 *
 * 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 2 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-2.0-or-later
 */

/* exported ActivitiesButton */

const { Clutter, St } = imports.gi;

const Main = imports.ui.main;

const ACTIVITIES_ICON = 1;
const ACTIVITIES_NONE = 2;

const KEY_SHOW_ACTIVITIES = 'show-activities';

var ActivitiesButton = class {
    constructor(settings) {
        this._currentChild = this._label = Main.panel.statusArea.activities._label;
        this._icon = new St.Icon({
            style_class: 'system-status-icon',
            icon_name: 'start-here-symbolic',
        });
        this._settings = settings;
        this._settingsChangedId = this._settings.connect('changed::%s'.format(KEY_SHOW_ACTIVITIES), this._onChangedShowActivities.bind(this));
        this._onChangedShowActivities();
    }

    _onChangedShowActivities() {
        let showActivities = this._settings.get_enum(KEY_SHOW_ACTIVITIES);
        if (showActivities === ACTIVITIES_ICON) {
            this._setChild(this._icon);
        } else {
            this._setChild(this._label);
        }
        this._setVisibility(showActivities !== ACTIVITIES_NONE);
    }

    _setChild(child) {
        if (!child || child === this._currentChild) return;
        let current = Main.panel.statusArea.activities.get_children()[0];
        Main.panel.statusArea.activities.remove_child(current);
        Main.panel.statusArea.activities.add_child(child);
        this._currentChild = child;
    }

    _setVisibility(visible) {
        if (Main.panel.statusArea.activities.container.visible === visible) return;
        Main.panel.statusArea.activities.container.visible = visible && Main.sessionMode.currentMode !== 'unlock-dialog';
        let rtl = Main.panel.get_text_direction() === Clutter.TextDirection.RTL;
        Main.panel._leftCorner.setStyleParent.call(Main.panel._leftCorner, Main.panel[rtl ? '_rightBox' : '_leftBox']);
    }

    destroy() {
        this._settings.disconnect(this._settingsChangedId);
        this._setChild(this._label);
        this._setVisibility(true);
        this._icon.destroy();
    }
};
