/*
 * Copyright (C) 2025  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.ui.util;

import javax.swing.*;

/**
 * Utility class for handling component mnemonics.
 */
public class MnemonicUtil {

    /**
     * Sets the text and mnemonic for an {@link AbstractButton} component.
     * The mnemonic character is specified in the text string using an ampersand (&) character.
     * For example, "&File" sets 'F' as the mnemonic for the button.
     * To display an actual ampersand character, use double ampersands "&&".
     * This code was taken from IntellIJ UI Designer's automatically generated $$$loadButtonText$$$().
     *
     * @param component The {@link AbstractButton} component to modify
     * @param text      The text to set, may contain a mnemonic character prefixed with &
     */
    public static void loadButtonText(AbstractButton component, String text) {
        StringBuilder result = new StringBuilder();
        boolean haveMnemonic = false;
        char mnemonic = '\0';
        int mnemonicIndex = -1;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == '&') {
                i++;
                if (i == text.length()) break;
                if (!haveMnemonic && text.charAt(i) != '&') {
                    haveMnemonic = true;
                    mnemonic = text.charAt(i);
                    mnemonicIndex = result.length();
                }
            }
            result.append(text.charAt(i));
        }
        component.setText(result.toString());
        if (haveMnemonic) {
            component.setMnemonic(mnemonic);
            component.setDisplayedMnemonicIndex(mnemonicIndex);
        }
    }

}