/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2023 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.installer.dialogs;

import org.jboss.installer.core.MnemonicUtils;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicOptionPaneUI;
import java.awt.event.ActionListener;

public class OptionPaneWithMnemonicsUI extends BasicOptionPaneUI {

    public static ComponentUI createUI(JComponent c) {
        return new OptionPaneWithMnemonicsUI();
    }

    @Override
    protected Object[] getButtons() {
        if (optionPane != null) {
            Object[] suppliedOptions = optionPane.getOptions();

            if (suppliedOptions == null) {
                return super.getButtons();
            } else {
                final JButton[] buttons = new JButton[suppliedOptions.length];
                final MnemonicUtils mnemonicUtils = new MnemonicUtils();

                for (int i = 0; i < suppliedOptions.length; i++) {
                    if ((suppliedOptions[i] instanceof JButton)) {
                        final ActionListener listener = createButtonActionListener(i);
                        JButton button = ((JButton) suppliedOptions[i]);
                        if (listener != null) {
                            button.addActionListener(listener);
                        }
                        mnemonicUtils.findMnemonic(button.getText(), true).ifPresent(button::setMnemonic);
                        buttons[i] = button;
                    }
                    else if ((suppliedOptions[i] instanceof String)) {
                        String t = (String) suppliedOptions[i];
                        final JButton button = new JButton(t);
                        mnemonicUtils.findMnemonic(t, true).ifPresent(button::setMnemonic);
                        final ActionListener listener = createButtonActionListener(i);
                        if (listener != null) {
                            button.addActionListener(listener);
                        }
                        buttons[i] = button;
                    } else {
                        return super.getButtons();
                    }
                }
                return buttons;
            }
        }
        return null;
    }
}
