/**
 *  Copyright © 2022-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.chat;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ComboBoxEditor;
import javax.swing.ComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nexuswob.gui.InputDocument;
import org.nexuswob.gui.swing.NimbusCellRenderer;
import net.javacomm.client.gui.JUserlist;
import net.javacomm.client.gui.MultilingualServiceButton;
import net.javacomm.client.resource.Resource;
import net.javacomm.multilingual.MultilingualButton;
import net.javacomm.multilingual.MultilingualLabel;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.protocol.ChatUser;
import net.javacomm.window.manager.Control;
import net.javacomm.window.manager.Frames;
import net.javacomm.window.manager.WindowManagerInternalFrame;



public class JGruppenraum extends WindowManagerInternalFrame {

  private final static Logger log = LogManager.getLogger(JGruppenraum.class);
  private static final long serialVersionUID = -8849895820719653247L;
  public final static int WIDTH = 500;
  public final static int HEIGHT = 530;
  private InternalAction internalAction = new InternalAction();
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private JPanel mainPane = new JPanel();
  private GridBagLayout gridbag = new GridBagLayout();
  private GridBagConstraints con = new GridBagConstraints();
  private JSeparator separator = new JSeparator();
  private JComboBox<String> rooms = new JComboBox<String>();
  private ButtonPanel buttonPanel = new ButtonPanel();
  private JUserlist myFriends = new JUserlist();
  private ArrowButtonPanel arrowPanel = new ArrowButtonPanel();
  private JUserlist userlist = new JUserlist();
  private JPanel outerpanel = new JPanel(true);
  private MultilingualServiceButton serviceButton = new MultilingualServiceButton(
      KEY.BUTTON_CONFIRM, KEY.BUTTON_SCHLIESSEN
  );
  private MultilingualLabel labelRaum = new MultilingualLabel(KEY.LABEL_RAEUME);
  private MultilingualLabel labelGruppenraumBeschreibung = new MultilingualLabel(
      KEY.LABEL_GRUPPENRAUM_BESCHREIBUNG
  );
  private Collection<String> referenceList = new ArrayList<>();
  private ItemListener itemListener;
  private ArrayList<ChatUser> eingangbenutzer;
  private JTextField comp;
  private ComboBoxEditor editor;
  private KeyAdapter raumAdapter = new KeyAdapter() {

    @Override
    public void keyReleased(KeyEvent event) {
      if (event.getKeyCode() == KeyEvent.VK_ENTER) return;
      if (comp.getText().length() == 0) {
        disableButtonRaumErstellen();
        return;
      }
      buttonPanel.buttonRaumerstellen.setBackground(Resource.JQUERY_GREEN);
      buttonPanel.buttonRaumerstellen.setForeground(Color.WHITE);
    }
  };

  public JGruppenraum() {
    init();
    setMinimumSize(new Dimension(480, 510));
  }



  @Override
  public void activated() {
    try {
      setSelected(true);
    }
    catch (PropertyVetoException e) {}
  }



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



  public synchronized void removeAllListener() {
    for (PropertyChangeListener listener : changes.getPropertyChangeListeners()) {
      removeCreateroomListener(listener);
    }
    removeInternalFrameListener(internalAction);
  }



  public void focusTo() {
    comp.requestFocusInWindow();
  }



  public final String getPassword() {
    return new String();
  }



  public final String getRoom() {
    return comp.getText();
  }



  /**
   * Der gerade eingerichtete Raum wurde vom Server bestätigt und wird in die
   * ComboBox aufgenommen.
   *
   * @param value
   *              ein Raum
   */
  public void setRoom(String value) {
    ComboBoxModel<String> model = rooms.getModel();
    int count = model.getSize();
    buttonPanel.buttonRaumerstellen.setBackground(Resource.JQUERY_RED);
    for (int index = 0; index < count; index++) {
      if (model.getElementAt(index).equals(value)) {
        return;
      }
    }
    // es gibt keine doppelten Einträge
    rooms.addItem(value);
    rooms.setSelectedItem(value);
    rooms.requestFocus();

  }



  @Override
  public Frames getType() {
    return Frames.GRUPPENRAUM;
  }



  @SuppressWarnings("serial")
  void init() {
    setContentPane(mainPane);
    mainPane.setLayout(gridbag);

    final int leftMargin = 12;
    final int rightMargin = 12;
    final int marginTop = 12;
    final int marginBottom = 12;

    con.gridx = 0;
    con.gridy = 0;
    con.gridwidth = 3;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.weightx = 1.0;
    con.weighty = 0.0;
    con.insets = new Insets(marginTop, leftMargin, 24, rightMargin);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(labelGruppenraumBeschreibung, con);
    mainPane.add(labelGruppenraumBeschreibung);
    labelGruppenraumBeschreibung.setIcon(new ImageIcon(getClass().getResource(Resource.GRUPPENRAUM)));

    con.gridx = 0;
    con.gridy = 1;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, leftMargin, 0, 0);
    con.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(labelRaum, con);
    mainPane.add(labelRaum);

    con.gridx = 0;
    con.gridy = 2;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, leftMargin, 0, 0);
    con.anchor = GridBagConstraints.WEST;

    gridbag.setConstraints(rooms, con);
    mainPane.add(rooms);
    rooms.setEditable(true);
    rooms.setRenderer(new NimbusCellRenderer<String>());
    editor = rooms.getEditor();
    comp = (JTextField) editor.getEditorComponent();
    comp.setDocument(new InputDocument(Resource.FELD_LEN_ROOM));
    comp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ENTER");
    comp.getActionMap().put("ENTER", new AbstractAction() {
      @Override
      public void actionPerformed(ActionEvent e) {
        buttonPanel.buttonRaumerstellen.doClick();
      }
    });
    comp.addKeyListener(raumAdapter);
    itemListener = new ItemListener() {
      @Override
      public void itemStateChanged(ItemEvent event) {
        if (event.getStateChange() == ItemEvent.SELECTED) {
          ComboBoxModel<String> model = rooms.getModel();
          String value = event.getItem().toString();
          int count = model.getSize();
          boolean found = false;
          for (int index = 0; index < count; index++) {
            found = found || model.getElementAt(index).equals(value);
          }
          if (found) {
            ComboBoxEditor editor = rooms.getEditor();
            final JTextField comp = (JTextField) editor.getEditorComponent();
            comp.setText(value);
            changes.firePropertyChange(JPausenraum.class.getName(), Control.NULL, Control.TOPICMEMBER);
          }
          else {
            // wird erkannt! bei Tastatur/ENTER
            // könnte genutzt werden für CREATE wird aber auch von
            // DELETE/ButtonKlick
            // erkannt ist nicht eindeutige
            // schwierig
            // log.info("neu=" + value);
          }
        }
      }
    };

    rooms.addItemListener(itemListener);

    con.gridx = 1;
    con.gridy = 2;
    con.gridwidth = 2;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 6, 0, rightMargin);
    con.anchor = GridBagConstraints.WEST;

    outerpanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    outerpanel.add(buttonPanel);

    gridbag.setConstraints(outerpanel, con);
    mainPane.add(outerpanel);

    con.gridx = 0;
    con.gridy = 3;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 1.0;
    con.weighty = 1.0;
    con.insets = new Insets(0, leftMargin, 0, 0);
    con.anchor = GridBagConstraints.CENTER;

    gridbag.setConstraints(myFriends, con);
    mainPane.add(myFriends);

    con.gridx = 1;
    con.gridy = 3;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 12, 0, 12);
    con.anchor = GridBagConstraints.CENTER;

    gridbag.setConstraints(arrowPanel, con);
    mainPane.add(arrowPanel);
    arrowPanel.addArrowButtonListener((event) -> {
      switch((Control) event.getNewValue()) {
        case CONFIRM:
          break;
        case SELECTED:
          List<String> selectedMembers = userlist.getSelectedMembers();
          if (selectedMembers.size() < 1) return;
          userlist.removeMember(selectedMembers);
          myFriends.setMember(selectedMembers);
          serviceButton.setEnabledButton1();
          break;
        default:
          log.warn("unbekannter Fall");
          break;
      }
    });

    con.gridx = 2;
    con.gridy = 3;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 1.0;
    con.weighty = 1.0;
    con.insets = new Insets(0, 0, 0, rightMargin);
    con.anchor = GridBagConstraints.CENTER;

    gridbag.setConstraints(userlist, con);
    mainPane.add(userlist);

    con.gridx = 0;
    con.gridy = 4;
    con.gridwidth = 3;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.weightx = 1.0;
    con.weighty = 0.0;
    con.insets = new Insets(24, leftMargin, 0, rightMargin);
    con.anchor = GridBagConstraints.CENTER;

    gridbag.setConstraints(separator, con);
    mainPane.add(separator);

    con.gridx = 1;
    con.gridy = 5;
    con.gridwidth = 2;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(12, leftMargin, marginBottom, rightMargin);
    con.anchor = GridBagConstraints.EAST;

    gridbag.setConstraints(serviceButton, con);
    add(serviceButton);
    serviceButton.addButtonListener(event -> {
      Control value = (Control) event.getNewValue();
      switch(value) {
        case BUTTON_1:
//          field = (JTextField) rooms.getEditor().getEditorComponent();
          String room = comp.getText();
          changes.firePropertyChange(room, Control.NULL, Control.UPDATE_CHATUSER);
          serviceButton.setDisabledButton1();
          break;
        case BUTTON_2:
          try {
            setClosed(true);
          }
          catch (PropertyVetoException e) {}
          break;
        default:
          break;
      }
    });
    serviceButton.setEnabledButton2();
    serviceButton.setDisabledButton1();
    addInternalFrameListener(internalAction);
  }



  /**
   * Der Knopf Raum erstellen wird rot angezeigt.
   * 
   */
  public void disableButtonRaumErstellen() {
    log.info("angekommen");
    buttonPanel.buttonRaumerstellen.setBackground(Resource.JQUERY_RED);
    buttonPanel.buttonRaumerstellen.setForeground(Color.WHITE);
  }



  /**
   * Gib alle Nicknames meiner Freunde zurück.
   *
   * @return die Nicknames aus meiner Freundesliste
   */
  public List<String> getNicknames() {
    return Collections.list(myFriends.getMembers());
  }



  /**
   *
   * Es werden nur die Mitglieder zurückgegeben, die tatsächlich neu sind. Alle
   * neuen Mitglieder werden zurückgegeben. Die neuen Mitglieder müssen in
   * TB_GRUPPE_USER abgelegt werden, damit sie sich anmelden können.
   *
   */
  public List<ChatUser> getNeueMitglieder() {
    ArrayList<ChatUser> chatuserlist = new ArrayList<>();
    myFriends.getMembers().asIterator().forEachRemaining((mitglied) -> {
      for (ChatUser benutzer : eingangbenutzer) {
        if (mitglied.equals(benutzer.getNickname())) {
          chatuserlist.add(benutzer);
          eingangbenutzer.remove(benutzer);
          break;
        }
      }
    });
    return chatuserlist;
  }



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



  /**
   * Alle möglichen Beitrittskandidaten werden übergeben.
   *
   * @param user
   *             eine Liste von Beitrittskandidaten
   */
  public void setCandidatemembers(ChatUser[] user) {
    if (user == null) return;
    eingangbenutzer = new ArrayList<>();
    for (ChatUser tmp : user) {
      eingangbenutzer.add(tmp);
    }
    int count = user.length;
    String[] member = new String[count];
    for (int index = 0; index < count; index++) {
      member[index] = user[index].getNickname();
    }
    userlist.clear();
    userlist.setMember(member);
  }



  void resetReferenceList(String member[]) {
    referenceList.clear();
    Collections.addAll(referenceList, member);
    serviceButton.setDisabledButton1();
  }



  public void setTopicmembers(ChatUser[] user) {
    if (user == null) return;
    int count = user.length;
    String[] member = new String[count];
    for (int index = 0; index < count; index++) {
      member[index] = user[index].getNickname();
    }
    myFriends.clear();
    myFriends.setMember(member);
    resetReferenceList(member);
  }



  /**
   * Eine Liste aller Pausenräume.
   *
   * @param value
   *              Pausenräume
   */
  public void setRooms(String... value) {
    if (value == null) return;
    // rooms.removeItemListener(itemListener);
    rooms.removeAllItems();
    for (String tmp : value) {
      rooms.addItem(tmp);
    }
    // rooms.addItemListener(itemListener); // hier ist der Fehler
    buttonPanel.buttonRaumerstellen.setBackground(Resource.JQUERY_RED);
  }

  private class ButtonPanel extends JPanel {

    private static final long serialVersionUID = 5384115606373922543L;
    private MultilingualButton buttonRaumerstellen = new MultilingualButton(KEY.BUTTON_RAUM_ERSTELLEN);

    private ButtonPanel() {
      super(true);
      setLayout(new GridLayout(1, 2, 6, 0));
      init();
    }



    private void init() {
      add(buttonRaumerstellen);
      buttonRaumerstellen.setForeground(Color.WHITE);
      buttonRaumerstellen.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
          String room = comp.getText();
          if (room.length() == 0) {
            buttonRaumerstellen.setBackground(Resource.JQUERY_RED);
            return;
          }
          changes.firePropertyChange(room, Control.NULL, Control.CREATE);
        }
      });
    }

  }

  private class InternalAction extends InternalFrameAdapter {

    @Override
    public void internalFrameClosed(InternalFrameEvent event) {
      arrowPanel.removeAllListener();
      comp.removeKeyListener(raumAdapter);
      rooms.removeItemListener(itemListener);
      changes.firePropertyChange(JBesprechungsraum.class.getName(), Control.NULL, Control.CLOSE);
    }
  }

  public enum room {
    publicroom,
    protectedroom
  }

  @Override
  public void setLanguage(ISO639 code) {
    serviceButton.setLanguage(KEY.BUTTON_CONFIRM, KEY.BUTTON_SCHLIESSEN, code);
    buttonPanel.buttonRaumerstellen.setLanguage(code);
    userlist.setHeader(KEY.LABEL_BENUTZER, code);
    myFriends.setHeader(KEY.LABEL_FREUNDE, code);
    labelRaum.setLanguage(code);
    setLanguage(KEY.GRUPPENRAUM_EINRICHTEN, code);
    labelGruppenraumBeschreibung.setLanguage(code);
    String help = labelGruppenraumBeschreibung.getText();
    labelGruppenraumBeschreibung.setText("<html>" + help + "</html>");
    arrowPanel.setLanguage(code);

  }



  @Override
  public void setBackgroundGradient(Color top, Color bottom) {
    windowManager.setBackgroundGradient(top, bottom);
  }

}
