/*********************************************************************
 * The Shortcuts is Copyright (C) 2016-2018 Kyle Robbertze
 * African Institute for Mathematical Sciences, South Africa
 *
 * Shortcuts is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation
 *
 * Shortcuts 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 Shortcuts.  If not, see <http://www.gnu.org/licenses/>.
 **********************************************************************/

import Gdk from "gi://Gdk";
import Gtk from "gi://Gtk";
import Gio from "gi://Gio";
import Adw from "gi://Adw";
import GObject from "gi://GObject";

import { ExtensionPreferences, gettext as _ } from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js";

const keyvalIsForbidden$1 = (keyval) => {
    return [
        Gdk.KEY_Home,
        Gdk.KEY_Left,
        Gdk.KEY_Up,
        Gdk.KEY_Right,
        Gdk.KEY_Down,
        Gdk.KEY_Page_Up,
        Gdk.KEY_Page_Down,
        Gdk.KEY_End,
        Gdk.KEY_Tab,
        Gdk.KEY_KP_Enter,
        Gdk.KEY_Return,
        Gdk.KEY_Mode_switch,
    ].includes(keyval);
};

const isValidAccel$1 = (mask, keyval) => {
    return Gtk.accelerator_valid(keyval, mask) || (keyval === Gdk.KEY_Tab && mask !== 0);
};

// eslint-disable-next-line complexity
const isValidBinding$1 = (mask, keycode, keyval) => {
    return !(
        mask === 0 ||
        (mask === Gdk.ModifierType.SHIFT_MASK &&
            keycode !== 0 &&
            ((keyval >= Gdk.KEY_a && keyval <= Gdk.KEY_z) ||
                (keyval >= Gdk.KEY_A && keyval <= Gdk.KEY_Z) ||
                (keyval >= Gdk.KEY_0 && keyval <= Gdk.KEY_9) ||
                (keyval >= Gdk.KEY_kana_fullstop && keyval <= Gdk.KEY_semivoicedsound) ||
                (keyval >= Gdk.KEY_Arabic_comma && keyval <= Gdk.KEY_Arabic_sukun) ||
                (keyval >= Gdk.KEY_Serbian_dje && keyval <= Gdk.KEY_Cyrillic_HARDSIGN) ||
                (keyval >= Gdk.KEY_Greek_ALPHAaccent && keyval <= Gdk.KEY_Greek_omega) ||
                (keyval >= Gdk.KEY_hebrew_doublelowline && keyval <= Gdk.KEY_hebrew_taf) ||
                (keyval >= Gdk.KEY_Thai_kokai && keyval <= Gdk.KEY_Thai_lekkao) ||
                (keyval >= Gdk.KEY_Hangul_Kiyeog && keyval <= Gdk.KEY_Hangul_J_YeorinHieuh) ||
                (keyval === Gdk.KEY_space && mask === 0) ||
                keyvalIsForbidden$1(keyval)))
    );
};

export default class AdwShortcutsPrefsWidget extends ExtensionPreferences {
    _onBtnClicked(btn, filechooser) {
        const parent = btn.get_root();
        filechooser.set_transient_for(parent);

        const shortcutsFileFilter = new Gtk.FileFilter();
        filechooser.set_filter(shortcutsFileFilter);
        shortcutsFileFilter.add_mime_type("application/json");

        filechooser.title = _("Select shortcut file");

        filechooser.show();
    }

    _updateshortcutsfile(adwrow) {
        const strshortcutsFile = this.getSettings().get_string("shortcuts-file");
        if (strshortcutsFile === "") return;
        adwrow.set_title(strshortcutsFile.split("/").pop());
        adwrow.set_subtitle(strshortcutsFile);
        adwrow.set_tooltip_text(strshortcutsFile);
    }

    _onFileChooserResponse(native, response) {
        if (response !== Gtk.ResponseType.ACCEPT) {
            return;
        }
        const fileURI = native.get_file().get_uri();
        const fileURI2 = fileURI.replace("file://", "");
        this.getSettings().set_string("shortcuts-file", fileURI2);
    }

    fillPreferencesWindow(window) {
        window.set_default_size(675, 750);
        window._settings = this.getSettings();
        let adwrow;
        const builder = Gtk.Builder.new();
        builder.add_from_file(this.path + "/ui/prefs.ui");
        const page1 = builder.get_object("Shortcuts_page_settings");

        const expadwrow = builder.get_object("Shortcuts_row_ownfile");
        const togglecustomfile = new Gtk.Switch({
            active: window._settings.get_boolean("use-custom-shortcuts"),
            valign: Gtk.Align.CENTER,
        });
        window._settings.bind("use-custom-shortcuts", togglecustomfile, "active", Gio.SettingsBindFlags.DEFAULT);

        expadwrow.set_expanded(togglecustomfile.get_active());
        expadwrow.add_suffix(togglecustomfile);
        expadwrow.activatable_widget = togglecustomfile;

        togglecustomfile.bind_property("active", expadwrow, "expanded", GObject.BindingFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_row_filename");
        this._updateshortcutsfile(adwrow);
        window._settings.connect("changed::shortcuts-file", this._updateshortcutsfile.bind(this, adwrow));

        const btnrowfilechooser = builder.get_object("Shortcuts_row_choosefile");
        const filechooser = new Gtk.FileChooserNative({
            title: _("Select shortcut file"),
            modal: true,
            action: Gtk.FileChooserAction.OPEN,
        });
        btnrowfilechooser.connect("activated", this._onBtnClicked.bind(this, btnrowfilechooser, filechooser));
        filechooser.connect("response", this._onFileChooserResponse.bind(this));

        adwrow = builder.get_object("Shortcuts_row_appspecificfiles");
        window._settings.bind("enable-appspecific-files", adwrow, "active", Gio.SettingsBindFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_switch_trayicon");
        window._settings.bind("show-icon", adwrow, "active", Gio.SettingsBindFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_row_transparency");
        window._settings.bind("use-transparency", adwrow, "active", Gio.SettingsBindFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_row_visibility");
        window._settings.bind("visibility", adwrow, "value", Gio.SettingsBindFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_row_maxcolumns");
        window._settings.bind("maxcolumns", adwrow, "value", Gio.SettingsBindFlags.DEFAULT);

        adwrow = builder.get_object("Shortcuts_row_hotkey");

        const shortcutLabel = new Gtk.ShortcutLabel({
            disabled_text: _("Select a hotkey"),
            accelerator: window._settings.get_strv("shortcuts-toggle-overview")[0],
            valign: Gtk.Align.CENTER,
            halign: Gtk.Align.CENTER,
        });
        window._settings.connect("changed::shortcuts-toggle-overview", () => {
            shortcutLabel.set_accelerator(window._settings.get_strv("shortcuts-toggle-overview")[0]);
        });
        adwrow.connect("activated", () => {
            const ctl = new Gtk.EventControllerKey();
            const content = new Adw.StatusPage({
                title: _("New hotkey"),
                icon_name: "preferences-desktop-keyboard-shortcuts-symbolic",
            });
            const editor = new Adw.Window({
                modal: true,
                transient_for: page1.get_root(),
                hide_on_close: true,
                width_request: 320,
                height_request: 240,
                resizable: false,
                content,
            });
            editor.add_controller(ctl);
            // eslint-disable-next-line no-shadow
            ctl.connect("key-pressed", (_, keyval, keycode, state) => {
                let mask = state & Gtk.accelerator_get_default_mod_mask();
                mask &= ~Gdk.ModifierType.LOCK_MASK;
                if (!mask && keyval === Gdk.KEY_Escape) {
                    editor.close();
                    return Gdk.EVENT_STOP;
                }
                if (!isValidBinding$1(mask, keycode, keyval) || !isValidAccel$1(mask, keyval)) {
                    return Gdk.EVENT_STOP;
                }
                window._settings.set_strv("shortcuts-toggle-overview", [
                    Gtk.accelerator_name_with_keycode(null, keyval, keycode, mask),
                ]);
                editor.destroy();
                return Gdk.EVENT_STOP;
            });
            editor.present();
        });
        adwrow.add_suffix(shortcutLabel);
        adwrow.activatable_widget = shortcutLabel;

        window.add(page1);
    }
}
