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

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolTip;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.nexuswob.gui.ArrowTooltip;
import org.nexuswob.gui.JToolTipBorder;
import org.nexuswob.gui.TableModel3;
import net.javacomm.client.environment.GUI;
import net.javacomm.client.resource.Resource;
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.protocol.Entry;
import net.javacomm.protocol.Lifetime;
import net.javacomm.protocol.Room;



public class JLauncherSelectRoom extends JScrollPane implements Babelfish {

  private static final long serialVersionUID = -4887422086783045526L;

  public final static int ONLINE = 0;
  public final static int ROOM = 1;
  public final static int ORT = 2;
  public final static int OWNER = 3;
  public final static int ENTRY = 4;
  public final static int LIFETIME = 5;
  private static MultilingualString online = new MultilingualString(KEY.STRING_ONLINE);
  private static MultilingualString room = new MultilingualString(KEY.STRING_RAUM);
  private static MultilingualString lebenszeit = new MultilingualString(KEY.STRING_LEBENSZEIT);
  private static MultilingualString ort = new MultilingualString(KEY.STRING_ORT);
  private static MultilingualString owner = new MultilingualString(KEY.STRING_EIGENTUEMER);
  private static MultilingualString entry = new MultilingualString(KEY.STRING_ZUTRITT);
  private final static String[] columns = {"Online", "Raum", "Ort", "Einrichter", "Zutritt", "Lebenszeit"};

  private int feld[] = {ONLINE, ROOM, ORT, OWNER, ENTRY, LIFETIME};
  private TableModel3 model3 = new TableModel3();
  private JTable table = new JTable();
  private MouseAction mouseAction = new MouseAction();
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);
  private TableColumn column;
  private TableColumnModel columnModel;
  private HeaderRenderer headerrenderer;
  private BarRenderer barrenderer = new BarRenderer();
  private ZutrittRenderer zutrittrenderer = new ZutrittRenderer();
  private MultilingualString tooltipText = new MultilingualString(KEY.STRING_DIE_SPALTEN_KOENNEN);

  @SuppressWarnings("serial")
  private JTableHeader header = new JTableHeader() {

    @Override
    public JToolTip createToolTip() {
      ToolTipManager.sharedInstance().setInitialDelay(200);
      ToolTipManager.sharedInstance().setDismissDelay(7000);
      ArrowTooltip arrow = new ArrowTooltip(Resource.JQUERY_BLAU);
      arrow.setComponent(header);
      arrow.setTextAttributes(GUI.regularFont13, Resource.JQUERY_HELLBLAU, Resource.JQUERY_BLAU);
      arrow.setBorder(new JToolTipBorder(7, Resource.JQUERY_YELLOW, Resource.JQUERY_BLAU));
      return arrow;
    }
  };

  public JLauncherSelectRoom() {
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(mouseAction);
    // table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setTableHeader(header);
    header.setBackground(Resource.JQUERY_HELLBLAU);

    model3.setHeader(columns);
    table.setModel(model3);
    table.setAutoCreateColumnsFromModel(false);

    KeyListener keyListener = new KeyListener() {

      @Override
      public void keyPressed(KeyEvent event) {
        int row = table.getSelectedRow();
        if (event.getKeyCode() == KeyEvent.VK_UP) {
          if (row < 2) {
            table.setRowSelectionInterval(2, 2);
            return;
          }
          try {
            table.setRowSelectionInterval(row - 1, row - 1);
          }
          catch (IllegalArgumentException e) {}
        }
        else if (event.getKeyCode() == KeyEvent.VK_DOWN) {
          if (row < 1) {
            table.setRowSelectionInterval(0, 0);
            return;
          }
          else if (row == table.getRowCount() - 1) {
            table.setRowSelectionInterval(row - 2, row - 2);
            return;
          }
          try {
            if (row == table.getRowCount() - 2) {
              table.setRowSelectionInterval(row - 1, row - 1);
              return;
            }
            table.setRowSelectionInterval(row + 1, row + 1);
          }
          catch (IllegalArgumentException e) {}
        }
        else if (event.getKeyCode() == KeyEvent.VK_ENTER) {
          if (row == -1) {
            return;
          }
          try {
            table.setRowSelectionInterval(row - 1, row - 1);
            Room room = new Room();
            room.setChatid(model3.getValueAt(row, feld[ROOM]).toString());
            room.setEntry(Entry.PUBLIC);

            // TODO aufpassen
//            room.setLifetime(Lifetime.valueOf(model.getValueAt (row, feld [LIFETIME]).toString()));

            String lebenszeit = (String) model3.getValueAt(row, feld[LIFETIME]);
            room.setLifetime(
                lebenszeit.equals(Lifetime.TEMPORARY.toString()) ? Lifetime.TEMPORARY : Lifetime.PERMANENT
            );

            room.setOwner(model3.getValueAt(row, feld[OWNER]).toString());
            /* keine Auswahl während einer Anfrage */
            changes.firePropertyChange(JLauncherSelectRoom.class.getName(), new Object(), room);
          }
          catch (IllegalArgumentException e) {}
        }
      }



      @Override
      public void keyReleased(KeyEvent arg0) {}



      @Override
      public void keyTyped(KeyEvent arg0) {}

    };
    table.addKeyListener(keyListener);

    barrenderer.setHorizontalAlignment(SwingConstants.HORIZONTAL);

    columnModel = table.getColumnModel();
    column = columnModel.getColumn(ROOM);
    column.setPreferredWidth(140);
    column.setCellRenderer(barrenderer);

    column = columnModel.getColumn(OWNER);
    column.setPreferredWidth(90);
    column.setCellRenderer(barrenderer);

    column = columnModel.getColumn(ORT);
    column.setPreferredWidth(70);
    column.setCellRenderer(zutrittrenderer);

    column = columnModel.getColumn(ENTRY);
    column.setPreferredWidth(75);
    column.setCellRenderer(zutrittrenderer);

    column = columnModel.getColumn(LIFETIME);
    column.setPreferredWidth(90);
    column.setCellRenderer(barrenderer);

    column = columnModel.getColumn(ONLINE);
    column.setCellRenderer(barrenderer);

    header.setColumnModel(columnModel);
    headerrenderer = new HeaderRenderer();
    header.setDefaultRenderer(headerrenderer);
    headerrenderer.setHorizontalAlignment(SwingConstants.CENTER);
    header.setPreferredSize(new Dimension(getPreferredSize().width, 32));

    header.setToolTipText("<html>" + tooltipText.toString() + "</html>");
    setViewportView(table);

    getViewport().setBackground(Resource.JQUERY_HELLBLAU);
  }

//
//  @Override
//  public Dimension getMinimumSize() {
//    return new Dimension(520, 0);
//  }
//



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



  public TableModel3 getModel() {
    return (model3);
  }



  @Override
  public void removeAll() {
    model3.removeAll();
  }



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



  public void setRowHeight(int row, int height) {
    table.setRowHeight(row, height);
  }

  /***************************************************************************/
  /*                                                                         */
  /* Innerclass MouseAction */
  /*                                                                         */
  /***************************************************************************/

  class MouseAction extends MouseAdapter {

    @Override
    public void mouseReleased(MouseEvent event) {
      Object obj;
      int row;

      obj = event.getSource();
      if (obj.equals(table)) {
        if (event.getClickCount() >= 2) {
          row = table.getSelectedRow();
          if (row % 2 == 0) return;
          Room room = new Room();
          room.setChatid(model3.getValueAt(row, feld[ROOM]).toString());
          JEntryLabel entrylabel = (JEntryLabel) model3.getValueAt(row, feld[ENTRY]);
          room.setEntry(entrylabel.getEntry());
          String lebenszeit = (String) model3.getValueAt(row, feld[LIFETIME]);
          room.setLifetime(
              lebenszeit.equals(Lifetime.TEMPORARY.toString()) ? Lifetime.TEMPORARY : Lifetime.PERMANENT
          );
          room.setOwner(model3.getValueAt(row, feld[OWNER]).toString());
          /* keine Auswahl während einer Anfrage */
          changes.firePropertyChange(JLauncherSelectRoom.class.getName(), new Object(), room);
        }
      }
    }
  }

  private class HeaderRenderer extends JLabel implements TableCellRenderer {
    private static final long serialVersionUID = 1483352116438614471L;

    public HeaderRenderer() {
      setOpaque(true);
    }



    @Override
    public Component getTableCellRendererComponent(JTable table, Object str, boolean isSelected,
        boolean hasFocus, int row, int column) {

      Border padding = BorderFactory.createEmptyBorder(1, 2, 1, 0);
      setBorder(BorderFactory.createCompoundBorder(padding, new LineBorder(Resource.JQUERY_BLAU, 2, true)));
      setBackground(Resource.JQUERY_HELLBLAU);
      setForeground(Resource.JQUERY_BLAU);
      setText((String) str);
      return this;
    }
  }

  @Override
  public void setLanguage(ISO639 code) {
    online.setLanguage(code);
    room.setLanguage(code);
    lebenszeit.setLanguage(code);
    ort.setLanguage(code);
    owner.setLanguage(code);
    entry.setLanguage(code);

    // TODO Spalte an der richtigen Position finden
    columnModel.getColumn(ONLINE).setHeaderValue(online.toString());
    columnModel.getColumn(ROOM).setHeaderValue(room.toString());
    columnModel.getColumn(LIFETIME).setHeaderValue(lebenszeit.toString());
    columnModel.getColumn(ORT).setHeaderValue(ort.toString());
    columnModel.getColumn(OWNER).setHeaderValue(owner.toString());
    columnModel.getColumn(ENTRY).setHeaderValue(entry.toString());

    tooltipText.setLanguage(code);
    header.setToolTipText("<html>" + tooltipText.toString() + "</html>");

  }

}
