/*
 * Zorin Screen Keyboard Button: Show a button to open the Screen
 * Keyboard in the panel if a touchscreen is present.
 *
 * Copyright (C) 2019 Zorin OS Technologies Ltd.
 *
 * 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/>.
 *
 */

const St = imports.gi.St;
const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const Clutter = imports.gi.Clutter;
const Lang = imports.lang;

let _screenKeyboardButton = null;


const ScreenKeyboardButton = new Lang.Class({
    Name: 'ScreenKeyboardButton',
    Extends: PanelMenu.Button,

    _init: function() {
        this.parent(null, "Screen Keyboard Button");

        let hbox = new St.BoxLayout({ style_class: 'panel-status-menu-box' });
        let icon = new St.Icon({ icon_name: 'input-keyboard-symbolic',
                                 style_class: 'system-status-icon' });

        hbox.add_child(icon);
        this.actor.add_child(hbox);

        this.actor.connect('button-press-event', this._toggleKeyboard);
    },

    _toggleKeyboard: function() {
        if (Main.keyboard._keyboardVisible) {
            Main.layoutManager.hideKeyboard();
        } else {
            Main.layoutManager.showKeyboard();
        }
    }
});

function init() {
}

function _isTouchscreenPresent() {
    let deviceManager = Clutter.DeviceManager.get_default();
    let result = false;

    deviceManager.list_devices().forEach(device => {
        if (device.get_device_type() == Clutter.InputDeviceType.TOUCHSCREEN_DEVICE)
            result = true;
    });

    return result;
}

function enable() {
    if (_isTouchscreenPresent() && _screenKeyboardButton == null) {
        _screenKeyboardButton = new ScreenKeyboardButton();
        Main.panel.addToStatusArea('screen-keyboard-button', _screenKeyboardButton, 0);
    }
}

function disable() {
    if (_screenKeyboardButton) {
        _screenKeyboardButton.destroy();
        _screenKeyboardButton = null;
    }
}