/**
 *  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.telko;

import java.awt.Color;
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.util.Collections;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import javax.swing.ToolTipManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nexuswob.gui.ArrowTooltip;
import org.nexuswob.gui.JToolTipBorder;
import net.javacomm.client.environment.GUI;
import net.javacomm.client.gui.JUserlist;
import net.javacomm.client.resource.Resource;
import net.javacomm.multilingual.Babelfish;
import net.javacomm.multilingual.MultilingualButton;
import net.javacomm.multilingual.MultilingualString;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.window.manager.Control;
import net.javacomm.window.manager.WMResource;



/**
 * Ein Zweilistenpanel, über welches Werte hin- und hergeschoben werden können.
 *
 * @author lromero
 *
 */
public class TwoPanelList extends JPanel implements Babelfish {

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

  private static final long serialVersionUID = -9101745604844305853L;

  private String property;
  private GridBagLayout gridbag = new GridBagLayout();
  private GridBagConstraints con = new GridBagConstraints();
  private JUserlist leftlist = new JUserlist();
  private ArrowPanel arrowPanel = new ArrowPanel();
  private JUserlist rightlist = new JUserlist();
  private MultilingualButton buttonEinladen = new MultilingualButton(KEY.BUTTON_EINLADEN);
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private ActionListener einladenListener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
      changes.firePropertyChange(ArrowPanel.class.getName(), Control.NULL, Control.INVITE);
    }

  };

  public TwoPanelList() {
    setLayout(gridbag);

    con.gridx = 0;
    con.gridy = 0;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 0, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(leftlist, con);
    add(leftlist);

    con.gridx++;
    con.gridy = 0;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 6, 0, 6);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(arrowPanel, con);
    add(arrowPanel);

    con.gridx++;
    con.gridy = 0;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.BOTH;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 0, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(rightlist, con);
    add(rightlist);

    con.gridx++;
    con.gridy = 0;
    con.gridwidth = 1;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 18, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(buttonEinladen, con);
    add(buttonEinladen);
    setEnabledButton(false);
  }



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



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



  public synchronized void removeAllListener() {
    for (PropertyChangeListener pl : changes.getPropertyChangeListeners()) {
      removeTeilnehmerListener(pl);
    }
    buttonEinladen.removeActionListener(einladenListener);
  }



  /**
   * Der linke Listenname wird gesetzt.
   *
   * @param header
   *               die Überschrift
   */
  public void setLeftlistName(String header) {
    leftlist.setHeader(header);
  }



  /**
   * Die linke Liste wird aufgefüllt.
   *
   *
   * @param array
   *              alle Nicknames
   */
  public void setLeftlist(List<String> array) {
    leftlist.setMember(array);
  }



  /**
   * Eine Teilnehmerliste wird zurückgegeben.
   *
   * @return die Liste enthält Nicknames
   */
  public List<String> getLeftlist() {
    return Collections.list(leftlist.getMembers());
  }



  public boolean getEnabledButton() {
    return buttonEinladen.getActionListeners().length > 0;
  }



  /**
   * Die Teilnehmerliste hat sich geändert. Der {@code Einladen} Knopf wird
   * aktiviert.
   *
   * @param enabled
   *                {@code true}, der Knopf ist aktiv
   */
  public void setEnabledButton(boolean enabled) {

    if (enabled) {
      if (buttonEinladen.getActionListeners().length == 0) {
        // addActionListener
        buttonEinladen.addActionListener(einladenListener);
      }
    }
    else {
      // removeActionListener
      buttonEinladen.removeActionListener(einladenListener);
    }

    buttonEinladen.setForeground(
        enabled ? WMResource.ENABLED_BUTTON_FOREGROUND : WMResource.DISABLED_BUTTON_FOREGROUND
    );
    buttonEinladen.setBackground(
        enabled ? WMResource.ENABLED_BUTTON_BACKGROUND : WMResource.DISABLED_BUTTON_BACKGROUND
    );

  }



  /**
   * Der Organisator darf nicht aus der Teilnehmerliste entfernt werden.
   *
   * @param organisator
   */
  public void setVeto(String organisator) {
    property = organisator;
  }



  /**
   * Die rechte Liste wird aufgefüllt.
   *
   *
   * @param array
   *              ein Feld mit Elemente
   */
  public void setRightlist(List<String> array) {
    rightlist.setMember(array);
  }



  /**
   * Lösche die rechte Liste
   *
   */
  public void clearRightlist() {
    rightlist.clear();
  }



  /**
   * Lösche die linke Liste
   *
   */
  public void clearLeftlist() {
    leftlist.clear();
  }



  /**
   * Der rechte Listenname wird gesetzt.
   *
   * @param header
   *               die Überschrift
   */
  public void setRightlistName(String header) {
    rightlist.setHeader(header);
  }

  /**
   *
   *
   *
   * @author llange
   *
   */
  private class ArrowPanel extends JPanel implements Babelfish {

    private static final long serialVersionUID = 779758453353282377L;
    private MultilingualString teilnehmerEinladen = new MultilingualString(
        KEY.STRING_BENUTZER_IN_DIE_TEILNEHMERLISTE
    );
    private MultilingualString teilnehmerVerabschieden = new MultilingualString(
        KEY.STRING_BENUTZER_AUS_DER_TEILNEHMERLISTE
    );
    @SuppressWarnings("serial")
    private JButton buttonLeft = new JButton() {
      @Override
      public JToolTip createToolTip() {
        ArrowTooltip arrow = new ArrowTooltip(Resource.JQUERY_ORANGE);
        arrow.setComponent(buttonLeft);
        arrow.setTextAttributes(GUI.regularFont13, Color.BLACK, Resource.JQUERY_ORANGE);
        arrow.setBorder(new JToolTipBorder(7, Resource.JQUERY_GREEN, Resource.JQUERY_ORANGE));
        return arrow;
      }
    };
    @SuppressWarnings("serial")
    private JButton buttonRight = new JButton() {
      @Override
      public JToolTip createToolTip() {
        ToolTipManager.sharedInstance().setInitialDelay(200);
        ToolTipManager.sharedInstance().setDismissDelay(4000);
        ArrowTooltip arrow = new ArrowTooltip(Resource.JQUERY_ORANGE);
        arrow.setComponent(buttonRight);
        arrow.setTextAttributes(GUI.regularFont13, Color.BLACK, Resource.JQUERY_ORANGE);
        arrow.setBorder(new JToolTipBorder(7, Resource.JQUERY_RED, Resource.JQUERY_ORANGE));
        return arrow;
      }
    };

    private Class<? extends ArrowPanel> clazz;

    private ArrowPanel() {
      super(true);
      setLayout(new GridLayout(2, 1));
      init();
    }



    /**
     * Hat sich die Freundesliste geändert?
     *
     */
    private void changedBuddies() {
      changes.firePropertyChange(ArrowPanel.class.getName(), Control.NULL, Control.MODIFY);
    }



    private void init() {
      clazz = getClass();
      buttonLeft.setIcon(new ImageIcon(clazz.getResource(Resource.LEFTARROW_25x26)));
      buttonLeft.setToolTipText(teilnehmerEinladen.toString());
      buttonLeft.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
          List<String> selectedMembers = rightlist.getSelectedMembers();
          rightlist.removeMember(selectedMembers);
          leftlist.setMember(selectedMembers);
          changedBuddies();
        }
      });
      buttonRight.setIcon(new ImageIcon(clazz.getResource(Resource.RIGHTARROW_25x26)));
      buttonRight.setToolTipText(teilnehmerVerabschieden.toString());
      buttonRight.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {

          // TODO blocken
          List<String> selectedMembers = leftlist.getSelectedMembers();
          boolean found = false;
          for (String temp : selectedMembers) {
            found = found || temp.equals(property);
          }
          if (found) return;
          rightlist.setMember(selectedMembers);
          leftlist.removeMember(selectedMembers);
          changedBuddies();
        }
      });

      add(buttonLeft);
      add(buttonRight);
    }



    @Override
    public void setLanguage(ISO639 code) {
      teilnehmerEinladen.setLanguage(code);
      buttonLeft.setToolTipText(teilnehmerEinladen.toString());
      teilnehmerVerabschieden.setLanguage(code);
      buttonRight.setToolTipText(teilnehmerVerabschieden.toString());
    }

  }

  @Override
  public void setLanguage(ISO639 code) {
    buttonEinladen.setLanguage(code);
    arrowPanel.setLanguage(code);
  }

}
