/**
 *  Copyright © 2026, 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.
 *
 */
package net.javacomm.client.chat;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nexuswob.gui.InputDocument;
import net.javacomm.multilingual.Babelfish;
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 JSearchTextfield extends JPanel implements Babelfish {

  private final static Logger log = LogManager.getLogger(JSearchTextfield.class);

  private static final ImageIcon MAGNIFYING_GLASS_ICON = createDummyMagnifyingGlassIcon();

  // Statische Hilfsmethode zur einmaligen Erstellung des Lupen-Icons
  private static ImageIcon createDummyMagnifyingGlassIcon() {
    int size = 24;
    BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = img.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

    g2.setColor(new Color(90, 90, 90));
    g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // Glas zeichnen
    g2.drawOval(3, 3, 12, 12);

    // Hintergrund ins Glas legen
    g2.setColor(new Color(220, 240, 255, 100));
    g2.fillOval(4, 4, 11, 11);

    // Griff zeichnen
    g2.setColor(new Color(90, 90, 90));
    g2.drawLine(14, 14, 21, 21);

    g2.dispose();
    return new ImageIcon(img);
  }

  private MultilingualString placeholder = new MultilingualString(KEY.STRING_SUCHEN_NACH);
  private final JTextField searchField;
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private boolean isFilter = false;

  public JSearchTextfield() {
    setLayout(new BorderLayout(5, 0));
    setOpaque(true);
    updateColors(); // Farben initialisieren

    setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.GRAY, 1), BorderFactory.createEmptyBorder(2, 5, 2, 5)
        )
    );

    // 1. Lupen-Icon (links)
    JLabel iconLabel = new JLabel(MAGNIFYING_GLASS_ICON);
    iconLabel.setOpaque(false);
    add(iconLabel, BorderLayout.WEST);

    // 2. Das Textfeld
    searchField = new JTextField(Constants.LEN_NICKNAME);

    // WICHTIG für Nimbus: Border komplett entfernen und Opaque auf false setzen,
    // damit das JTextField keinen eigenen grauen/weißen Kasten malt.
    searchField.setBorder(BorderFactory.createEmptyBorder());
    searchField.setOpaque(false);
    searchField.setBackground(new Color(0, 0, 0, 0)); // Transparent erzwingen

    searchField.addFocusListener(new java.awt.event.FocusAdapter() {
      @Override
      public void focusGained(FocusEvent event) {
        if (searchField.getText().equals(placeholder.toString())) {
          searchField.setText("");
        }
      }



      @Override
      public void focusLost(java.awt.event.FocusEvent e) {
        if (searchField.getText().isEmpty()) {
          searchField.setText(placeholder.toString());
        }
      }
    });

    // Live-Suche Event
    searchField.setDocument(new InputDocument(Constants.LEN_NICKNAME));
    searchField.getDocument().addDocumentListener(new DocumentListener() {
      @Override
      public void changedUpdate(DocumentEvent e) {
        checkSearch();
      }



      @Override
      public void insertUpdate(DocumentEvent e) {
        checkSearch();
      }



      @Override
      public void removeUpdate(DocumentEvent e) {
        checkSearch();
      }
    });

    add(searchField, BorderLayout.CENTER);
  }



  public void addSearchfieldListener(PropertyChangeListener listener) {
    changes.addPropertyChangeListener(listener);
  }



  private void checkSearch() {
    if (getText().equals(placeholder.toString())) return; // Suchen nach nichts auslösen
    changes.firePropertyChange(JSearchTextfield.class.getName(), Control.NULL, Control.HIT);
  }



  /**
   * Gibt den reinen Suchtext zurück (ignoriert den Platzhalter).
   */
  public String getQuery() {
    String text = searchField.getText();
    return text.equals(placeholder.toString()) ? "" : text;
  }



  public String getText() {
    return searchField.getText();
  }



  /**
   * Indicates whether the filter field contains at least one character.
   *
   * @return {@code true} if the filter field contains at least one character
   */
  public boolean isFilter() {
    if (getText().equals(placeholder.toString())) {
      return false; // kein Filter
    }
    if (getText().isEmpty()) {
      // kein Filter
      return false;
    }
    else {
      return true;
    }
  }



  public void removeSearchFieldListener(PropertyChangeListener listener) {
    changes.removePropertyChangeListener(listener);
  }



  @Override
  public void setBackground(Color bg) {
    super.setBackground(bg);
    if (searchField != null) {
      searchField.setBackground(new Color(0, 0, 0, 0));
    }
  }



  @Override
  public void setLanguage(ISO639 code) {
    placeholder.setLanguage(code);
    searchField.setText(placeholder.toString());
  }



  /**
   * Holt die aktuelle Hintergrundfarbe vom UIManager (unterstützt dynamische
   * Schemas).
   */
  public void updateColors() {
    Color bg = UIManager.getColor("TextField.background");
    if (bg != null) {
      super.setBackground(bg);
    }
    if (searchField != null) {
      searchField.setBackground(new Color(0, 0, 0, 0));
    }
  }

}