/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2021 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.panels.frame;

import org.jboss.installer.actions.QuitAction;
import org.jboss.installer.common.UiResources;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.MnemonicUtils;
import org.jboss.installer.core.Navigator;
import org.jboss.installer.navigation.NavigationState;

import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.HashSet;
import java.util.Set;

public class NavigationPanel extends JPanel implements NavigationState.Observer {

    private static final String NAV_NEXT_KEY = "navigation.next";
    private static final String NAV_PREV_KEY = "navigation.previous";
    private static final String NAV_QUIT_KEY = "navigation.quit";
    private static final String NAV_DONE_KEY = "navigation.done";
    private final LanguageUtils langUtils;
    private final Navigator navigator;
    private final NavigationState navState;
    private final QuitAction quitAction;
    private JButton nextButton;
    private JButton previousButton;
    private JButton quitButton;
    private JButton doneButton;

    public NavigationPanel(Navigator navigator, NavigationState navState, LanguageUtils langUtils, QuitAction quitAction) {
        this.navigator = navigator;
        this.navState = navState;
        this.navState.registerObserver(this);
        this.langUtils = langUtils;
        this.quitAction = quitAction;
        initPanel();
    }

    private void initPanel() {
        nextButton = UiResources.createButton(langUtils.getString(NAV_NEXT_KEY), actionEvent -> navigator.moveToNext());
        previousButton = UiResources.createButton(langUtils.getString(NAV_PREV_KEY), actionEvent -> navigator.moveToPrevious());
        quitButton = UiResources.createButton(langUtils.getString(NAV_QUIT_KEY), actionEvent -> quitAction.actionPerformed());
        doneButton = UiResources.createButton(langUtils.getString(NAV_DONE_KEY), actionEvent -> quitAction.actionPerformed());

        // assign mnemonics to global buttons
        final MnemonicUtils mnemonicUtils = new MnemonicUtils();
        final Set<Character> reserved = new HashSet<>();
        assignMnemonic(mnemonicUtils, quitButton, reserved);
        assignMnemonic(mnemonicUtils, nextButton, reserved);
        assignMnemonic(mnemonicUtils, previousButton, reserved);
        assignMnemonic(mnemonicUtils, doneButton, reserved);
        MnemonicUtils.reserveGlobal(reserved);

        this.setLayout(new FlowLayout(FlowLayout.RIGHT));
        this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        this.add(nextButton);
        this.add(previousButton);
        this.add(quitButton);
        this.add(doneButton);

        // monitor focus to update the NavState
        nextButton.addFocusListener(new FocusLostAdapter());
        previousButton.addFocusListener(new FocusLostAdapter());
        quitButton.addFocusListener(new FocusLostAdapter());
        doneButton.addFocusListener(new FocusLostAdapter());
    }

    private void assignMnemonic(MnemonicUtils mnemonicUtils, JButton quitButton, Set<Character> reserved) {
        mnemonicUtils.findMnemonic(quitButton.getText()).ifPresent(c -> {
            reserved.add(c);
            quitButton.setMnemonic(c);
        });
    }

    private boolean navHasFocus() {
        return nextButton.hasFocus() || previousButton.hasFocus() ||
                quitButton.hasFocus() || doneButton.hasFocus();
    }

    @Override
    public void changed() {
        if (navState.isNextEnabled() && navState.isNextVisible()) {
            if (navState.isFocus()) {
                nextButton.requestFocus();
            }
            this.getRootPane().setDefaultButton(nextButton);
        } else if (navState.isDoneVisible()) {
            if (navState.isFocus()) {
                doneButton.requestFocus();
            }
            this.getRootPane().setDefaultButton(doneButton);
        } else if (navState.isErrorState()) {
            if (navState.isFocus()) {
                quitButton.requestFocus();
            }
            this.getRootPane().setDefaultButton(quitButton);
        }

        nextButton.setEnabled(navState.isNextEnabled());
        nextButton.setVisible(navState.isNextVisible());
        previousButton.setVisible(navState.isPreviousVisible());
        previousButton.setEnabled(navState.isPreviousEnabled());
        quitButton.setVisible(navState.isQuitVisible());
        doneButton.setVisible(navState.isDoneVisible());
        revalidate();
    }

    public JButton getNextButton() {
        return nextButton;
    }

    private class FocusLostAdapter extends FocusAdapter {
        @Override
        public void focusLost(FocusEvent e) {
            if (!navHasFocus()) {
                navState.lostFocus();
            }
        }
    }
}