/**
 *  Copyright © 2020-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.filetransfer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.nexuswob.gui.InputDocument;
import org.nexuswob.gui.swing.NimbusCellRenderer;
import org.nexuswob.util.Util;
import net.javacomm.client.environment.GUI;
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.window.manager.Control;



/*****************************************************************************/
/*                                                                           */
/*                                Class JLookingFor                          */
/*                                                                           */
/*****************************************************************************/

public class JFTServiceSuchmuster extends JPanel implements Babelfish {

  private static final long serialVersionUID = 203724238883104009L;

  private MultilingualLabel labelLookingFor = new MultilingualLabel(KEY.LABEL_SUCHEN_NACH);
  private JList<String> listFiles = new JList<String>();
  private DefaultListModel<String> model = new DefaultListModel<String>();
  private JScrollPane scroll = new JScrollPane();
  private ButtonPane buttonPane = new ButtonPane();
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private Class<? extends JFTServiceSuchmuster> resource;
  private BoxLayout boxlayout;
  private JPanel toplabel = new JPanel(new BorderLayout());
  private final MultilingualString ABBRECHEN = new MultilingualString(KEY.STRING_SCHLIESSEN);
  private final MultilingualString SPEICHERN = new MultilingualString(KEY.STRING_SPEICHERN);
  private MultilingualString suchmuster = new MultilingualString(KEY.STRING_SUCHMUSTER);
  private MultilingualString joker = new MultilingualString(KEY.STRING_JOKER);

  private final Dimension maxsize = new Dimension(222, 244);

  public JFTServiceSuchmuster() {
    boxlayout = new BoxLayout(this, BoxLayout.Y_AXIS);
    setLayout(boxlayout);

    resource = getClass();

    labelLookingFor.setIcon(new ImageIcon(resource.getResource(Resource.FIND)));
    labelLookingFor.setForeground(Resource.JQUERY_ORANGE);
    labelLookingFor.setFont(GUI.regularBold);
    labelLookingFor.setHorizontalAlignment(SwingConstants.LEFT);

    toplabel.add(labelLookingFor);
    toplabel.add(BorderLayout.NORTH, labelLookingFor);

    listFiles.setModel(model);
    listFiles.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    listFiles.setVisibleRowCount(7);
    listFiles.setCellRenderer(new NimbusCellRenderer<>());
    listFiles.setBackground(Color.WHITE);
    scroll.setViewportView(listFiles);

    toplabel.add(BorderLayout.CENTER, scroll);
    add(toplabel);
    add(Box.createRigidArea(new Dimension(0, 6)));
    add(buttonPane);
  }



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



  private void addSearchFile(String str) {
    if (model.size() == 0) {}
    model.addElement(str);
  }



  @Override
  public Dimension getMaximumSize() {
    return maxsize;
  }



  @Override
  public Dimension getMinimumSize() {
    return maxsize;
  }



  @Override
  public Dimension getPreferredSize() {
    return maxsize;
  }



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



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

  /*****************************************************************************/
  /*                                                                           */
  /* Innerclass ButtonPane */
  /*                                                                           */
  /*****************************************************************************/

  class ButtonPane extends JPanel implements ActionListener {

    private static final long serialVersionUID = -7567060751078359666L;
    private GridLayout grid = new GridLayout(2, 1, 0, 6);
    private MultilingualButton buttonSuchmuster = new MultilingualButton(KEY.BUTTON_SUCHMUSTER_ANLEGEN);
    private MultilingualButton buttonRemove = new MultilingualButton(KEY.BUTTON_SUCHMUSTER_ENTFERNEN);
    private Class<? extends ButtonPane> resource;
    private ImageIcon anaranjado;

    public ButtonPane() {
      resource = getClass();
      setLayout(grid);
      anaranjado = new ImageIcon(getClass().getResource(Resource.FRAGEZEICHEN_46x48));
      buttonSuchmuster.setIcon(new ImageIcon(resource.getResource(Resource.SEARCH)));

      buttonSuchmuster.setHorizontalAlignment(JButton.LEFT);
      buttonSuchmuster.addActionListener(this);
      add(buttonSuchmuster);

      buttonRemove.setIcon(new ImageIcon(resource.getResource(Resource.REMOVE)));

      buttonRemove.addActionListener(this);
      buttonRemove.setHorizontalAlignment(JButton.LEFT);
      add(buttonRemove);

    }



    @SuppressWarnings("serial")
    @Override
    public void actionPerformed(ActionEvent event) {
      Object obj;

      obj = event.getSource();
      if (obj.equals(buttonSuchmuster)) {

        if (model.size() == 64) {
          JOptionPane.showMessageDialog(
              JFTServiceSuchmuster.this,
              "<html>" + "<head/>"
                  + "<body>"
                  + "Die Anzahl der Suchmuster ist auf 64 begrenzt."
                  + "</body>"
                  + "</html>",
              "Suche Datei", JOptionPane.INFORMATION_MESSAGE
          );
          return;
        }

        Object[] options = new Object[] {SPEICHERN, ABBRECHEN};
        JOptionPane pane = new JOptionPane(
            joker.toString(), JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, anaranjado, options
        );
        pane.setWantsInput(true);
        InputDocument document = new InputDocument(20);
        List<Component> result = Util.getAllComponents(pane);

        JTextField textfield = null;
        for (Component component : result) {
          if (component instanceof JTextField) {
            textfield = (JTextField) component;
            textfield.setDocument(document);
            textfield.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ENTER");
            textfield.getActionMap().put("ENTER", new AbstractAction() {
              @Override
              public void actionPerformed(ActionEvent e) {
                for (Component comp : result) {
                  if (!(comp instanceof JButton)) continue;
                  JButton help = (JButton) comp;
                  if (help.getText().equals(SPEICHERN.toString())) {

                    help.doClick();
                    break;
                  }
                }
              }
            });
          }
          else if (component instanceof JButton button) {
            if (button.getText().equals(ABBRECHEN.toString())) {
//              button.setMnemonic(Mnemonics.SCHLIESSEN.getMnemonic());
              button.addActionListener((eventSchliessen) -> {
                pane.setValue("");
              });
            }
            else if (button.getText().equals(SPEICHERN.toString())) {
//              button.setMnemonic(Mnemonics.SPEICHERN.getMnemonic());
            }
          }
        }
        
        JInternalFrame question = pane.createInternalFrame(JFTServiceSuchmuster.this, suchmuster.toString());
        question.addInternalFrameListener(new InternalFrameAdapter() {
          @Override
          public void internalFrameClosing(InternalFrameEvent e) {
            Object input = pane.getInputValue();
            if (input == JOptionPane.UNINITIALIZED_VALUE) return;
            String item = (String) input;
            if (model.contains(item)) return;
            if (item.length() > 0) {
              addSearchFile(item);
              changes.firePropertyChange(ButtonPane.this.getName(), model.elements(), Control.SEARCH);
            }
          }

        });
        question.setMaximizable(false);
        question.setResizable(false);
        question.setIconifiable(false);
        question.setClosable(false);
        question.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        question.setFrameIcon(new ImageIcon(resource.getResource(Resource.FIND)));
        question.show();

      }
      else if (obj.equals(buttonRemove)) {

        List<String> indices = listFiles.getSelectedValuesList();
        for (int index = 0; index < indices.size(); index++) {
          model.removeElement(indices.get(index));
        }
        changes.firePropertyChange("JLookingFor", model.elements(), Control.SEARCH);
        if (model.size() > 0) {
          return;
        }

      }
    }

  }

  @Override
  public void setLanguage(ISO639 code) {
    labelLookingFor.setLanguage(code);
    buttonPane.buttonSuchmuster.setLanguage(code);
    buttonPane.buttonRemove.setLanguage(code);
    ABBRECHEN.setLanguage(code);
    SPEICHERN.setLanguage(code);
    suchmuster.setLanguage(code);
    joker.setLanguage(code);
  }

}
