/* extension.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 init */

const Clutter = imports.gi.Clutter;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const ViewSelector = imports.ui.viewSelector;
const EdgeDragAction = imports.ui.edgeDragAction;
const WindowManager = imports.ui.windowManager;
const St = imports.gi.St;
const Gio = imports.gi.Gio;

class Extension {
    constructor() {
	this._settings = ExtensionUtils.getSettings();
	let actions = global.stage.get_actions();

	actions.forEach(a => {
	    if (a instanceof ViewSelector.ShowOverviewAction)
		this._showOverview = a;
	    else if (a instanceof WindowManager.AppSwitchAction)
		this._appSwitch = a;
	    else if (a instanceof EdgeDragAction.EdgeDragAction &&
		     a._side == St.Side.BOTTOM)
		this._showOsk = a;
	    else if (a instanceof EdgeDragAction.EdgeDragAction &&
		     a._side == St.Side.TOP)
		this._unfullscreen = a;
	    else if (a instanceof EdgeDragAction.EdgeDragAction)
		this._showAppGrid = a;
	});

	this._map = [
	    { setting: 'overview', action: this._showOverview },
	    { setting: 'app-switch', action: this._appSwitch },
	    { setting: 'show-osk', action: this._showOsk },
	    { setting: 'unfullscreen', action: this._unfullscreen },
	    { setting: 'show-app-grid', action: this._showAppGrid }
	];
    }

    enable() {
	this._map.forEach(m => {
	    this._settings.bind(m.setting, m.action, 'enabled',
				Gio.SettingsBindFlags.GET);
            m.handler = m.action.connect('notify::enabled', () => {
                if (m.action.enabled && !this._settings.get_boolean(m.setting))
                    m.action.enabled = this._settings.get_boolean(m.setting);
            });
	});
    }

    disable() {
	this._map.forEach(m => {
	    m.action.enabled = true;
            if (m.handler > 0)
                m.action.disconnect(m.handler);
	});
    }
}

function init() {
    return new Extension();
}
