/**
 *  Copyright © 2021-2025, Luis Andrés Lange <https://javacomm.net>
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  ----------------------------------------------------------------------------
 *
 *  Exhibit B - "Incompatible With Secondary Licenses" Notice
 *
 *  This Source Code Form is "Incompatible With Secondary Licenses",
 *  as defined by the Mozilla Public License, v. 2.0.
 *
 *  In short:
 *  - This file may be used, modified, and distributed under MPL 2.0 only.
 *  - It may NOT be relicensed under GPL, LGPL, AGPL, or any other Secondary License.
 *
 *  Rationale:
 *  - Ensures that the code remains MPL-2.0.
 *  - Avoids legal conflicts with GPL-licensed libraries (e.g., VideoLAN).
 *  - Maximizes usability for commercial and security-critical applications.
 *
 */
package net.javacomm.client.administer;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import org.nexuswob.gui.InputDocument;
import org.nexuswob.util.Util;
import net.javacomm.client.gui.MultilingualServiceButton;
import net.javacomm.client.resource.Resource;
import net.javacomm.multilingual.Babelfish;
import net.javacomm.multilingual.MultilingualButton;
import net.javacomm.multilingual.MultilingualLabel;
import net.javacomm.multilingual.MultilingualString;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.share.Constants;
import net.javacomm.window.manager.Control;



@SuppressWarnings("serial")
public class JSpitzname extends JPanel implements Babelfish {


  private GridBagLayout gridbag = new GridBagLayout();
  private GridBagConstraints con = new GridBagConstraints();
  private MultilingualLabel labelEinleitung = new MultilingualLabel(KEY.LABEL_EIN_VERBOTENER_SPITZNAME);
  private MultilingualLabel labelNicknames = new MultilingualLabel(KEY.LABEL_VERBOTENE_SPITZNAMEN);
  private JScrollPane scrollpane = new JScrollPane();
  private DefaultListModel<String> model = new DefaultListModel<>();
  private JList<String> listFilter = new JList<>(model);
  private JSeparator separator = new JSeparator();

  private JPanel buttonVerwalten = new JPanel();
  private GridLayout gridVerwalten = new GridLayout(2, 1, 0, 12);
  private MultilingualButton buttonAdd = new MultilingualButton(KEY.BUTTON_SPITZNAME_HINZUFUEGEN);
  private MultilingualButton buttonRemove = new MultilingualButton(KEY.BUTTON_SPITZNAME_ENTFERNEN);
  private ActionListener addActionListener;
  private ActionListener removeActionListener;
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private MultilingualString verbotenerSpitzname = new MultilingualString(KEY.STRING_VERBOTENER_SPITZNAME);
  private MultilingualServiceButton serviceButton = new MultilingualServiceButton(
      KEY.BUTTON_SPEICHERN, KEY.BUTTON_SCHLIESSEN
  );
  private MultilingualString spitzname = new MultilingualString(KEY.LABEL_SPITZNAME);
  private ImageIcon fragezeichen;
  private URL iconFragezeichen;

  private final int margin_top = 12;
  private final int margin_left = 12;
  private final int margin_right = 12;

  public JSpitzname() {
    setLayout(gridbag);

    con.gridx = 0;
    con.gridy = 0;
    con.gridwidth = 2;
    con.gridheight = 1;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(margin_top, margin_left, 0, margin_right);
    con.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(labelEinleitung, con);
    add(labelEinleitung);


    con.gridx = 0;
    con.gridy++;
    con.gridwidth = 1;
    con.gridheight = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(margin_top, margin_left, 0, margin_right);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(labelNicknames, con);
    add(labelNicknames);

    con.gridx = 0;
    con.gridy++;
    con.gridwidth = 1;
    con.gridheight = 1;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 1.0;
    con.weighty = 1.0;
    con.insets = new Insets(0, margin_left, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(scrollpane, con);
    add(scrollpane);
    scrollpane.setViewportView(listFilter);
    scrollpane.getHorizontalScrollBar().setUnitIncrement(12);
    scrollpane.getVerticalScrollBar().setUnitIncrement(12);
    listFilter.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    con.gridx = 1;
    con.gridy = 2;
    con.gridwidth = 1;
    con.gridheight = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 0, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(buttonVerwalten, con);
    add(buttonVerwalten);
    buttonVerwalten.setLayout(gridVerwalten);
    buttonVerwalten.add(buttonAdd);
    buttonVerwalten.add(buttonRemove);
    iconFragezeichen = getClass().getResource(Resource.FRAGEZEICHEN_46x48);
    fragezeichen = new ImageIcon(iconFragezeichen);
    addActionListener = new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        final String ABBRECHEN = serviceButton.getButton_2_Text();
        final String OK = serviceButton.getButton_1_Text();
        Object[] options = new Object[] {OK, ABBRECHEN};
        JOptionPane pane = new JOptionPane(
            verbotenerSpitzname.toString(), JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION,
            fragezeichen,
            options
        );
        pane.setWantsInput(true);

        InputDocument document = new InputDocument(Constants.LEN_NICKNAME);
        List<Component> result = Util.getAllComponents(pane);
        result.forEach((component) -> {
          if (component instanceof JTextField) {
            JTextField textfield = (JTextField) component;
            textfield.setDocument(document);
          }
//          else if (component instanceof JButton) {
//            JButton button = (JButton) component;
//            if (button.getText().equals(ABBRECHEN)) {
//              button.setMnemonic(Mnemonics.SCHLIESSEN.getMnemonic());
//            }
//            else if (button.getText().equals(OK)) {
//              button.setMnemonic(Mnemonics.SPEICHERN.getMnemonic());
//            }
//          }
        });

        JDialog dialog = pane.createDialog(JSpitzname.this, spitzname.toString());
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setAlwaysOnTop(true);
        dialog.setModal(true);
        dialog.pack();
        dialog.setVisible(true);
        Object input = pane.getValue();
        if (input == null) return;
        if (input == JOptionPane.UNINITIALIZED_VALUE) return;
        if (input.equals(ABBRECHEN)) return;
        String item = (String) pane.getInputValue();
        if (model.contains(item)) return;
        model.addElement(item);


      }
    };
    buttonAdd.addActionListener(addActionListener);

    removeActionListener = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        List<String> selectedValues = listFilter.getSelectedValuesList();
        selectedValues.forEach((value) -> {
          model.removeElement(value);
        });
      }
    };
    buttonRemove.addActionListener(removeActionListener);


    con.gridx = 0;
    con.gridy++;
    con.gridwidth = 2;
    con.gridheight = 1;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(24, margin_left, 0, margin_right);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(separator, con);
    add(separator);

    con.gridx = 1;
    con.gridy++;
    con.gridwidth = 1;
    con.gridheight = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(12, margin_left, 12, margin_right);
    con.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(serviceButton, con);
    add(serviceButton);
    serviceButton.addButtonListener(event -> {
      Control value = (Control) event.getNewValue();
      switch(value) {
        case BUTTON_1:
          changes.firePropertyChange(JSpitzname.class.getName(), 0, Control.SAVE);
          break;
        case BUTTON_2:
          changes.firePropertyChange(JSpitzname.class.getName(), 0, Control.CLOSE);
          break;
        default:
          break;
      }

    });
    serviceButton.setEnabledButton1();

  }







  public synchronized void addNicknamesListener(PropertyChangeListener l) {
    changes.addPropertyChangeListener(l);
  }



  public synchronized void removeNicknamesListener(PropertyChangeListener l) {
    changes.removePropertyChangeListener(l);
  }



  public synchronized void removeAllListener() {
    serviceButton.removeAllListener();
    for (PropertyChangeListener listener : changes.getPropertyChangeListeners()) {
      removeNicknamesListener(listener);
    }
    for (ActionListener al : buttonRemove.getActionListeners()) {
      buttonRemove.removeActionListener(al);
    }
    for (ActionListener al : buttonAdd.getActionListeners()) {
      buttonAdd.removeActionListener(al);
    }
  }



  public Enumeration<String> getNicknames() {
    return model.elements();
  }



  /**
   * Die verbotenen Nicknames.
   *
   * @param nicknames
   *                  verbotene Nicknames
   */
  public void setNicknames(List<String> nicknames) {
    model.clear();
    model.addAll(nicknames);
  }



  @Override
  public void setLanguage(ISO639 code) {
    serviceButton.setLanguage(code);
    spitzname.setLanguage(code);
    labelNicknames.setLanguage(code);
    buttonAdd.setLanguage(code);
    buttonRemove.setLanguage(code);
    labelEinleitung.setLanguage(code);
    verbotenerSpitzname.setLanguage(code);
  }

}
