/* showDesktop.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 ShowDesktopButton */

const { GObject, Shell, St } = imports.gi;

const ExtensionUtils = imports.misc.extensionUtils;

const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;

const _ = ExtensionUtils.gettext;

var ShowDesktopButton = GObject.registerClass(
class ShowDesktopButton extends PanelMenu.Button {
    _init() {
        super._init(0.0, _('Show Desktop'), true);
        this.add_child(new St.Icon({
            style_class: 'system-status-icon',
            icon_name: 'video-display-symbolic',
        }));
        this.connect('button-press-event', this._onButtonPressEvent.bind(this));
        this._windows = [];
    }

    _onButtonPressEvent() {
        let tracker = Shell.WindowTracker.get_default();
        let workspace = global.workspace_manager.get_active_workspace();
        let workspaceIndex = workspace.index();
        let workspaceWindows = workspace.list_windows();
        if (this._windows[workspaceIndex]) {
            workspaceWindows.forEach(window => {
                if (tracker.get_window_app(window)) {
                    let restore = true;
                    for (let i = 0; i < this._windows[workspaceIndex].length; i++) {
                        if (window === this._windows[workspaceIndex][i]) {
                            restore = false;
                            break;
                        }
                    }
                    if (restore) window.unminimize();
                }
            });
            this._windows[workspaceIndex] = null;
        } else {
            this._windows[workspaceIndex] = [];
            workspaceWindows.forEach(window => {
                if (tracker.get_window_app(window)) {
                    let canClose = window.can_close ? window.can_close() : true;
                    if (canClose && !window.minimized) {
                        window.minimize();
                    } else {
                        this._windows[workspaceIndex].push(window);
                    }
                }
            });
        }
        Main.overview.hide();
    }
});
