/* keyboard.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 KeyboardMenuButton */

const { GLib } = imports.gi;

const Main = imports.ui.main;
const PopupMenu = imports.ui.popupMenu;

const { InputSourceIndicator } = imports.ui.status.keyboard;

const KEY_ALWAYS_SHOW_INPUT_SOURCE_STATUS = 'always-show-input-sources-status';

var KeyboardMenuButton = class {
    constructor(settings) {
        this._settings = settings;
        this._settingsChangedId = this._settings.connect('changed::%s'.format(KEY_ALWAYS_SHOW_INPUT_SOURCE_STATUS), this._onChangedAlwaysShowInputSourceStatus.bind(this));
        this._onChangedAlwaysShowInputSourceStatus();
        GLib.timeout_add(GLib.PRIORITY_DEFAULT, 200, () => {
            this._currentSourceChanged();
            return GLib.SOURCE_REMOVE;
        });
    }

    _currentSourceChanged() {
        Main.panel.statusArea.keyboard._currentSourceChanged.call(Main.panel.statusArea.keyboard);
    }

    _onChangedAlwaysShowInputSourceStatus() {
        this._setOverride(this._settings.get_boolean(KEY_ALWAYS_SHOW_INPUT_SOURCE_STATUS));
    }

    _setOverride(isOverride) {
        if (isOverride) {
            Main.panel.statusArea.keyboard._currentSourceChanged = function(manager, oldSource) {
                InputSourceIndicator.prototype._currentSourceChanged.call(this, manager, oldSource);
                if (Object.keys(this._inputSourceManager.inputSources).length === 1) {
                    this.show();
                    this._menuItems[0].setOrnament(PopupMenu.Ornament.DOT);
                    this._menuItems[0].setSensitive(false);
                    this._indicatorLabels[0].show();
                }
            };
        } else {
            Main.panel.statusArea.keyboard._currentSourceChanged = InputSourceIndicator.prototype._currentSourceChanged;
        }
        this._currentSourceChanged();
    }

    destroy() {
        this._settings.disconnect(this._settingsChangedId);
        this._setOverride(false);
    }
};
