// gpl v3
// Based on:
// https://github.com/maoschanz/Move-OSD-Windows-GNOME-Extension/issues/2 --> Thank you @maoschanz
// https://discourse.gnome.org/t/how-can-i-move-the-workspace-switcher-popup-to-the-right/6940 --> Thank you @GdH

const Main = imports.ui.main;
const WorkspaceSwitcherPopup = imports.ui.workspaceSwitcherPopup;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;

let initWSP;

function init() {
	Convenience.initTranslations();
	initWSP = WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show;
}

//------------------------------------------------------------------------------

function injectToFunction(parent, name, func) {
	let origin = parent[name];
	parent[name] = function() {
		let ret;
		ret = origin.apply(this, arguments);
			if (ret === undefined)
				ret = func.apply(this, arguments);
			return ret;
		}
	return origin;
}

function removeInjection(object, injection, name) {
	if (injection[name] === undefined)
		delete object[name];
	else
		object[name] = injection[name];
}

let injections=[];

//------------------------------------------------------------------------------

function enable() {
	let settings = Convenience.getSettings('org.gnome.shell.extensions.move-workspaceSwitcherPopup');

	injections['_redisplay'] = injectToFunction(
		WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype, '_redisplay', function() {
			
			if(settings.get_boolean('hide')) {
				WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show = function() { return false };
			} else {
				WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show = initWSP;
				let workArea = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);
				let [, containerNatHeight] = this._container.get_preferred_height(global.screen_width);
				let [, containerNatWidth] = this._container.get_preferred_width(containerNatHeight);
				let h_percent = settings.get_int('horizontal');
				let v_percent = settings.get_int('vertical');

				this._container.x = workArea.x + Math.floor((workArea.width - containerNatWidth) * (h_percent/100));
				this._container.y = workArea.y + Math.floor((workArea.height - containerNatHeight) * (v_percent/100));				
			}
		}
	);
}

function disable() {
	WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype._show = initWSP;
	removeInjection(WorkspaceSwitcherPopup.WorkspaceSwitcherPopup.prototype, injections, '_redisplay');
}
