import Atk from 'gi://Atk';
import Clutter from 'gi://Clutter';
import GObject from 'gi://GObject';
import Pango from 'gi://Pango';
import Shell from 'gi://Shell';
import St from 'gi://St';

import * as Main from './main.js';
import * as Params from '../misc/params.js';
import * as PopupMenu from './popupMenu.js';

export class EntryMenu extends PopupMenu.PopupMenu {
    constructor(entry) {
        super(entry, 0, St.Side.TOP);

        this._entry = entry;
        this._clipboard = St.Clipboard.get_default();

        // Populate menu
        let item;
        item = new PopupMenu.PopupMenuItem(_('Copy'));
        item.connect('activate', this._onCopyActivated.bind(this));
        this.addMenuItem(item);
        this._copyItem = item;

        item = new PopupMenu.PopupMenuItem(_('Paste'));
        item.connect('activate', this._onPasteActivated.bind(this));
        this.addMenuItem(item);
        this._pasteItem = item;

        if (entry instanceof St.PasswordEntry)
            this._makePasswordItem();

        Main.uiGroup.add_child(this.actor);
        this.actor.hide();
    }

    _makePasswordItem() {
        const item = new PopupMenu.PopupMenuItem('');
        item.connect('activate', this._onPasswordActivated.bind(this));
        this.addMenuItem(item);
        this._passwordItem = item;

        this._entry.bind_property('show-peek-icon',
            this._passwordItem, 'visible',
            GObject.BindingFlags.SYNC_CREATE);
    }

    open(params = {}) {
        if (!super.open(params))
            return false;

        this._updatePasteItem();
        this._updateCopyItem();
        if (this._passwordItem)
            this._updatePasswordItem();

        this._entry.add_style_pseudo_class('focus');

        const direction = St.DirectionType.TAB_FORWARD;
        if (!this.actor.navigate_focus(null, direction, false))
            this.actor.grab_key_focus();
        return true;
    }

    _updateCopyItem() {
        const selection = this._entry.clutter_text.get_selection();
        this._copyItem.setSensitive(!this._entry.clutter_text.password_char &&
                                    selection && selection !== '');
    }

    _updatePasteItem() {
        this._clipboard.get_text(St.ClipboardType.CLIPBOARD,
            (clipboard, text) => {
                this._pasteItem.setSensitive(text && text !== '');
            });
    }

    _updatePasswordItem() {
        if (!this._entry.password_visible)
            this._passwordItem.label.set_text(_('Show Text'));
        else
            this._passwordItem.label.set_text(_('Hide Text'));
    }

    _onCopyActivated() {
        const selection = this._entry.clutter_text.get_selection();
        this._clipboard.set_text(St.ClipboardType.CLIPBOARD, selection);
    }

    _onPasteActivated() {
        this._clipboard.get_text(St.ClipboardType.CLIPBOARD,
            (clipboard, text) => {
                if (!text)
                    return;
                this._entry.clutter_text.delete_selection();
                const pos = this._entry.clutter_text.get_cursor_position();
                this._entry.clutter_text.insert_text(text, pos);
            });
    }

    _onPasswordActivated() {
        this._entry.password_visible  = !this._entry.password_visible;
    }
}

function _setMenuAlignment(entry, stageX) {
    const [success, entryX] = entry.transform_stage_point(stageX, 0);
    if (success)
        entry.menu.setSourceAlignment(entryX / entry.width);
}

function _onMenuClickGesture(gesture, entry) {
    if (entry.menu.isOpen) {
        entry.menu.close();
    } else if (gesture.get_button() === Clutter.BUTTON_SECONDARY) {
        const coords = gesture.get_coords_abs();
        _setMenuAlignment(entry, coords.x);
        entry.menu.open();
    }
}

function _onPopup(actor, entry) {
    const cursorPosition = entry.clutter_text.get_cursor_position();
    const [success, textX, textY_, lineHeight_] = entry.clutter_text.position_to_coords(cursorPosition);
    if (success)
        entry.menu.setSourceAlignment(textX / entry.width);
    entry.menu.open();
}

/**
 * @param {St.Entry} entry
 * @param {*} params
 */
export function addContextMenu(entry, params) {
    if (entry.menu)
        return;

    params = Params.parse(params, {actionMode: Shell.ActionMode.POPUP});

    entry.menu = new EntryMenu(entry);
    entry._menuManager = new PopupMenu.PopupMenuManager(entry, {
        actionMode: params.actionMode,
    });
    entry._menuManager.addMenu(entry.menu);

    const clickGesture = new Clutter.ClickGesture();
    clickGesture.set_recognize_on_press(true);
    clickGesture.set_required_button(Clutter.BUTTON_SECONDARY);
    clickGesture.connect(
        'recognize', gesture => _onMenuClickGesture(gesture, entry));
    entry.add_action_full(
        'menu-click-gesture', Clutter.EventPhase.CAPTURE, clickGesture);

    entry.connect('popup-menu', actor => _onPopup(actor, entry));

    entry.connect('destroy', () => {
        entry.menu.destroy();
        entry.menu = null;
        entry._menuManager = null;
    });
}

export const CapsLockWarning = GObject.registerClass(
class CapsLockWarning extends St.Label {
    _init(params) {
        super._init({
            style_class: 'caps-lock-warning-label',
            ...params,
        });

        this.text = _('Caps lock is on');

        this.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
        this.clutter_text.line_wrap = true;

        const backend = this.get_context().get_backend();
        const seat = backend.get_default_seat();
        this._keymap = seat.get_keymap();

        this.connect('notify::mapped', () => {
            if (this.is_mapped()) {
                this._keymap.connectObject(
                    'state-changed', () => this._sync(true), this);
            } else {
                this._keymap.disconnectObject(this);
            }

            this._sync(false);
        });
    }

    _sync(animate) {
        const capsLockOn = this._keymap.get_caps_lock_state();

        this.remove_all_transitions();

        const {naturalHeightSet} = this;
        this.natural_height_set = false;
        const [, height] = this.get_preferred_height(-1);
        this.natural_height_set = naturalHeightSet;

        if (capsLockOn) {
            this.add_accessible_state(Atk.StateType.SHOWING);
            this.add_accessible_state(Atk.StateType.VISIBLE);
        } else {
            this.remove_accessible_state(Atk.StateType.SHOWING);
            this.remove_accessible_state(Atk.StateType.VISIBLE);
        }

        this.ease({
            height: capsLockOn ? height : 0,
            opacity: capsLockOn ? 255 : 0,
            duration: animate ? 200 : 0,
            onComplete: () => {
                if (capsLockOn)
                    this.height = -1;
            },
        });
    }
});
