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

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.javacomm.client.gui.MultilingualServiceButton;
import net.javacomm.client.resource.Resource;
import net.javacomm.multilingual.MultilingualCheckBox;
import net.javacomm.multilingual.MultilingualLabel;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.protocol.UserOnline;
import net.javacomm.window.manager.Control;
import net.javacomm.window.manager.Frames;
import net.javacomm.window.manager.WM;
import net.javacomm.window.manager.WindowAnrufenEvent;
import net.javacomm.window.manager.WindowAnrufenListener;
import net.javacomm.window.manager.WindowManagerInternalFrame;



public class EinwilligungInternalFrame extends WindowManagerInternalFrame implements WindowAnrufenListener {

  private final static Logger log = LogManager.getLogger(EinwilligungInternalFrame.class);
  private static final long serialVersionUID = -2992619214506326740L;
  public final static int SCREEN_WIDTH = TeilenInternalFrame.SCREEN_WIDTH;
  public final static int SCREEN_HEIGHT = 330;
  private String record = "";
  private ImageIcon image;
  private GridBagLayout gridbag = new GridBagLayout();
  private GridBagConstraints con = new GridBagConstraints();
  private MultilingualLabel label = new MultilingualLabel(KEY.LABEL_FUER_DEN_EMPFANG);
  private JSeparator separator = new JSeparator();
  private JComboBox<String> benutzerliste = new JComboBox<>();
  private PropertyChangeSupport changes = new PropertyChangeSupport(this);

  private InternalFrameAdapter internalFrameAdapter = new InternalFrameAdapter() {
    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
      changes.firePropertyChange(EinwilligungInternalFrame.class.getName(), Control.NULL, Control.CLOSE);
    }

  };
  private MultilingualCheckBox checkbox = new MultilingualCheckBox(KEY.CHECK_BOX_EMPFANG);
  private MultilingualServiceButton serviceButton = new MultilingualServiceButton(
      KEY.BUTTON_SPEICHERN_SCHLIESSEN, KEY.BUTTON_SCHLIESSEN
  );
  private JSplitPane splitpaneHorizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
  private JScrollPane leftpanel = new JScrollPane();
  private JPanel setuppanel = new JPanel();

  public EinwilligungInternalFrame() {
    setMaximizable(false);
    setResizable(true);
    setIconifiable(true);
    setClosable(true);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    setFrameTitleId("Bildschirmempfang");
    URL url = getClass().getResource(Resource.CONSENT_39x26);
    image = new ImageIcon(url);
    setFrameIcon(image);
    setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    addInternalFrameListener(internalFrameAdapter);
    init();
  }



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



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



  @Override
  public String getFrameTitleId() {
    return record;
  }



  @Override
  public Dimension getMinimumSize() {
    return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
  }



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



  private void init() {

    setContentPane(splitpaneHorizontal);

    leftpanel.setViewportView(setuppanel);
    leftpanel.getVerticalScrollBar().setUnitIncrement(12);
    leftpanel.getHorizontalScrollBar().setUnitIncrement(12);
    leftpanel.setBorder(null);
    splitpaneHorizontal.setLeftComponent(leftpanel);
    splitpaneHorizontal.setRightComponent(windowManager);
    splitpaneHorizontal.setDividerLocation(SCREEN_WIDTH - WindowManagerInternalFrame.SPLITWIDTH);
    splitpaneHorizontal.setOneTouchExpandable(true);
    windowManager.setMinimumSize(new Dimension(0, 0));
    windowManager.addWMListener(new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent event) {
        changes.firePropertyChange(event);
      }
    });

    setuppanel.setLayout(gridbag);

    // 1. Reihe
    con.gridx = 0;
    con.gridy = 0;
    con.gridwidth = 4;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(0, 0, 0, 0);
    con.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(label, con);
    setuppanel.add(label);

    // 2. Reihe
    con.gridx = 0;
    con.gridy = 1;
    con.gridwidth = 4;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(12, 0, 0, 0);
    con.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(checkbox, con);
    setuppanel.add(checkbox);

    // 3. Reihe
    con.gridx = 0;
    con.gridy++;
    con.gridwidth = 4;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(24, 0, 0, 0);
    con.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(separator, con);
    setuppanel.add(separator);

    con.gridx = 0;
    con.gridy++;
    con.gridwidth = 4;
    con.fill = GridBagConstraints.NONE;
    con.weightx = 0.0;
    con.weighty = 0.0;
    con.insets = new Insets(12, 0, 12, 0);
    con.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(serviceButton, con);
    setuppanel.add(serviceButton);
    serviceButton.setEnabledButton1();
    serviceButton.addButtonListener(event -> {
      Control value = (Control) event.getNewValue();
      switch(value) {
        case BUTTON_1:
          changes.firePropertyChange(
              EinwilligungInternalFrame.class.getName(), Control.NULL, Control.SAVE_AND_CLOSE
          );
          try {
            setClosed(true);
          }
          catch (PropertyVetoException e) {}
          break;
        case BUTTON_2:
          changes.firePropertyChange(EinwilligungInternalFrame.class.getName(), Control.NULL, Control.CLOSE);
          try {
            setClosed(true);
          }
          catch (PropertyVetoException e) {}
          break;
        default:
          break;
      }
    });
  }



  @Override
  public void insertWM(WM value) {
    windowManager.addWindow(value);
  }



  /**
   * Soll der Dienst gestartet werden?
   * 
   * @return {@code true}, der Dienst soll gestartet werden
   */
  public boolean isOnrekorder() {
    return checkbox.isSelected();
  }



  public synchronized void removeAllListener() {
    for (PropertyChangeListener listener : changes.getPropertyChangeListeners()) {
      removeScreensaverListener(listener);
    }
    windowManager.removeAllListener();
  }



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



  @Override
  public void removeWM(WM frame) {
    windowManager.removeWM(frame);
  }



  @Override
  public void ringRing(WindowAnrufenEvent event) {
    extText = event.getNickname();
    getMultiAbnehmen().setLanguage(KEY.FRAME_ABNEHMEN, event.getCode(), extText);
    getMultiAnrufen().setLanguage(KEY.TELEFON_ANRUFEN, event.getCode(), extText);
  }



  @Override
  public void setFrameTitleId(String id) {
    record = id;
    setTitle(record);
  }



  @Override
  public void setLanguage(ISO639 code) {
    checkbox.setLanguage(code);
    serviceButton.setLanguage(KEY.BUTTON_SPEICHERN_SCHLIESSEN, KEY.BUTTON_SCHLIESSEN, code);
    label.setLanguage(code);

    setLanguage(KEY.FRAME_EINWILLIGUNG, code); // der neue Name wird gesetzt
    treeView(code);
  }



  /**
   * Markiere die Checkbox Bildschirmdaten empfangen.
   * 
   * 
   * @param value
   *              {@code true}, Bildschirmdaten können empfangen werden.
   */
  public void setOnrekorder(boolean value) {
    checkbox.setSelected(value);
  }



  @Override
  public void setType(Frames value) {
    log.warn("Der Typ wurde mit Frames.SCREENRECEIVER statisch vorgegeben.");
  }



  /**
   * Eine Benutzerliste wird übergeben. Die Benutzerliste enthält Nicknames. Nach
   * dem Aufruf enthält die Combobox nur die Nicknames aus der übergebenen Liste.
   * 
   * 
   * 
   * @param liste
   *              eine Liste von Nicknames
   */
  public void setUserList(UserOnline[] liste) {
    benutzerliste.removeAllItems();
    for (UserOnline online : liste) {
      benutzerliste.addItem(online.getNickname());
    }
  }



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

}
