/*
 * 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.FrameImages;
import org.jboss.installer.Installer;
import org.jboss.installer.common.UiResources;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.MnemonicUtils;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import static org.jboss.installer.screens.DefaultScreen.SUBSECTION_INSET;

/**
 * Displays a language picker for Installer. Should be displayed before the rest of Installer is loaded.
 */
public class LanguageDialog extends JDialog {

    public static final String LANGUAGE_DIALOG_INFO_KEY = "language_dialog.info";
    private JComboBox<LocaleWrapper> selector;
    // don't use LanguageUtils here - we need the default system locale ResourceBundle
    private final ResourceBundle translations = ResourceBundle.getBundle(LanguageUtils.I18N_BUNDLE);
    private boolean canceled = false;


    public LanguageDialog() {
        // magically makes the dialog appear in the alt+tab/task bar
        super((Dialog)null);
        initUI();

        this.setIconImages(FrameImages.icons);
    }

    public void display() {
        setModal(true);
        toFront();
        setVisible(true);
    }

    public Locale getSelectedLocale() {
        return ((LocaleWrapper)selector.getSelectedItem()).getLocale();
    }

    public boolean isCanceled() {
        return canceled;
    }

    private void initUI() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                LanguageDialog.this.canceled = true;
                LanguageDialog.this.dispose();

                System.exit(0);
            }
        });

        setTitle(Installer.getInstallerFrameTitle());

        final JPanel contentPane = (JPanel) getContentPane();

        GridBagLayout layout = new GridBagLayout();
        contentPane.setLayout(layout);
        GridBagConstraints c = UiResources.initializeConstraints();
        c.ipady=8;

        ImageIcon img = getImage();
        JLabel imgLabel = new JLabel(img);
        contentPane.add(imgLabel);

        final String instruction = translations.getString(LANGUAGE_DIALOG_INFO_KEY);
        JLabel descLabel = new JLabel(instruction, SwingConstants.LEADING);
        c.gridy = 1;
        c.insets = SUBSECTION_INSET;
        layout.addLayoutComponent(descLabel, c);
        contentPane.add(descLabel);

        selector = new JComboBox<>(getLanguages());
        c.insets = new Insets(10,10,10,10);
        c.gridy = 3;
        layout.addLayoutComponent(selector, c);
        contentPane.add(selector);

        JButton okButton = UiResources.createButton(translations.getString("generic.ok"), actionEvent -> dispose());
        new MnemonicUtils().findMnemonic(okButton.getText()).ifPresent(okButton::setMnemonic);
        c.fill = GridBagConstraints.NONE;
        c.gridy = 4;
        layout.addLayoutComponent(okButton, c);
        contentPane.add(okButton);
        getRootPane().setDefaultButton(okButton);

        resizeAndCenter();
        okButton.grabFocus();
    }

    private LocaleWrapper[] getLanguages() {
        return LanguageUtils.AVAILABLE_LOCALES.stream()
                .map(LocaleWrapper::new)
                .collect(Collectors.toList())
                .toArray(new LocaleWrapper[] {});
    }

    private void resizeAndCenter() {
        setSize(getPreferredSize());
        pack();
        Dimension frameSize = getSize();
        Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setLocation(center.x - frameSize.width / 2, center.y - frameSize.height / 2 - 10);
        setResizable(false);
    }

    public ImageIcon getImage() {
        ImageIcon img;
        try {
            img = new ImageIcon(LanguageDialog.class.getResource("/img/logo4clearspace.png"));
        } catch (NullPointerException err) {
            img = null;
        }
        return img;
    }

    static class LocaleWrapper {

        private final Locale locale;

        LocaleWrapper(Locale locale) {
            this.locale = locale;
        }

        public Locale getLocale() {
            return locale;
        }

        @Override
        public String toString() {
            return locale.getDisplayLanguage(locale);
        }
    }


}
