/** Opens the currently selected chat. */
  void openChatForSelection() {
    Object selectedValue = this.chatRoomsTableModel.getValueAt(this.chatRoomList.getSelectedRow());

    ChatRoomWrapper chatRoomWrapper;
    if (selectedValue instanceof ChatRoomWrapper) chatRoomWrapper = (ChatRoomWrapper) selectedValue;
    else return;

    if (!chatRoomWrapper.getChatRoom().isJoined()) {
      GuiActivator.getUIService().getConferenceChatManager().joinChatRoom(chatRoomWrapper);
    }

    ChatWindowManager chatWindowManager = GuiActivator.getUIService().getChatWindowManager();
    ChatPanel chatPanel = chatWindowManager.getMultiChat(chatRoomWrapper, true);

    chatWindowManager.openChat(chatPanel, true);
  }
  /** Removes the room that is currently selected. */
  void removeSelectedRoom() {
    ChatRoomWrapper chatRoomWrapper = chatRoomsTableModel.getValueAt(chatRoomList.getSelectedRow());

    ConferenceChatManager conferenceManager =
        GuiActivator.getUIService().getConferenceChatManager();
    conferenceManager.removeChatRoom(chatRoomWrapper);
  }
  private String getNickname() {
    String nickName = null;
    ChatOperationReasonDialog reasonDialog =
        new ChatOperationReasonDialog(
            GuiActivator.getResources().getI18NString("service.gui.CHANGE_NICKNAME"),
            GuiActivator.getResources().getI18NString("service.gui.CHANGE_NICKNAME_LABEL"));

    reasonDialog.setReasonFieldText("");

    int result = reasonDialog.showDialog();

    if (result == MessageDialog.OK_RETURN_CODE) {
      nickName = reasonDialog.getReason().trim();
    }

    return nickName;
  }
示例#4
0
  /**
   * Handles the <tt>ActionEvent</tt>, when one of the tool bar buttons is clicked.
   *
   * @param e the <tt>ActionEvent</tt> that notified us
   */
  public void actionPerformed(ActionEvent e) {
    AbstractButton button = (AbstractButton) e.getSource();
    String buttonText = button.getName();

    ChatPanel chatPanel = chatContainer.getCurrentChat();

    if (buttonText.equals("previous")) {
      chatPanel.loadPreviousPageFromHistory();
    } else if (buttonText.equals("next")) {
      chatPanel.loadNextPageFromHistory();
    } else if (buttonText.equals("sendFile")) {
      SipCommFileChooser scfc =
          GenericFileDialog.create(
              null,
              "Send file...",
              SipCommFileChooser.LOAD_FILE_OPERATION,
              ConfigurationUtils.getSendFileLastDir());
      File selectedFile = scfc.getFileFromDialog();
      if (selectedFile != null) {
        ConfigurationUtils.setSendFileLastDir(selectedFile.getParent());
        chatContainer.getCurrentChat().sendFile(selectedFile);
      }
    } else if (buttonText.equals("invite")) {
      ChatInviteDialog inviteDialog = new ChatInviteDialog(chatPanel);

      inviteDialog.setVisible(true);
    } else if (buttonText.equals("leave")) {
      ChatRoomWrapper chatRoomWrapper =
          (ChatRoomWrapper) chatPanel.getChatSession().getDescriptor();
      ChatRoomWrapper leavedRoomWrapped =
          GuiActivator.getMUCService().leaveChatRoom(chatRoomWrapper);
    } else if (buttonText.equals("call")) {
      call(false, false);
    } else if (buttonText.equals("callVideo")) {
      call(true, false);
    } else if (buttonText.equals("desktop")) {
      call(true, true);
    } else if (buttonText.equals("options")) {
      GuiActivator.getUIService().getConfigurationContainer().setVisible(true);
    } else if (buttonText.equals("font")) chatPanel.showFontChooserDialog();
    else if (buttonText.equals("createConference")) {
      chatPanel.showChatConferenceDialog();
    }
  }
示例#5
0
  /** Sets the names of the call buttons depending on the chat session type. */
  private void setCallButtonsName() {
    if (chatSession instanceof ConferenceChatSession) {
      callButton.setName("createConference");
      callVideoButton.setName("createConference");
      this.callButton.setToolTipText(
          GuiActivator.getResources().getI18NString("service.gui.CREATE_JOIN_VIDEO_CONFERENCE"));

      this.callVideoButton.setToolTipText(
          GuiActivator.getResources().getI18NString("service.gui.CREATE_JOIN_VIDEO_CONFERENCE"));
    } else {
      callButton.setName("call");
      callVideoButton.setName("callVideo");
      this.callButton.setToolTipText(
          GuiActivator.getResources().getI18NString("service.gui.CALL_CONTACT"));

      this.callVideoButton.setToolTipText(
          GuiActivator.getResources().getI18NString("service.gui.CALL_CONTACT"));
    }
  }
  /**
   * Creates an instance of <tt>ChatRoomConfigurationWindow</tt> and initializes the configuration
   * form.
   *
   * @param chatRoomName the name of the room
   * @param configForm the configuration form to load in this configuration window
   */
  public ChatRoomConfigurationWindow(String chatRoomName, ChatRoomConfigurationForm configForm) {
    super(false);

    this.configForm = configForm;

    this.setTitle(
        GuiActivator.getResources()
            .getI18NString("service.gui.CHAT_ROOM_CONFIGURATION", new String[] {chatRoomName}));

    titlePanel.setTitleText(
        GuiActivator.getResources().getI18NString("service.gui.CHAT_ROOM_OPTIONS"));

    this.generalScrollPane.setPreferredSize(new Dimension(820, 520));
    this.generalScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    this.generalScrollPane.setOpaque(false);
    this.generalScrollPane.getViewport().setOpaque(false);

    this.mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

    this.mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    this.saveButton.addActionListener(this);
    this.cancelButton.addActionListener(this);

    this.buttonsPanel.add(saveButton);
    this.buttonsPanel.add(cancelButton);

    this.generalScrollPane.getViewport().add(mainPanel);

    this.getContentPane().add(titlePanel, BorderLayout.NORTH);
    this.getContentPane().add(generalScrollPane, BorderLayout.CENTER);
    this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);

    titlePanel.setOpaque(false);
    buttonsPanel.setOpaque(false);
    mainPanel.setOpaque(false);
    generalScrollPane.setOpaque(false);

    this.loadConfigurationForm();
  }
示例#7
0
  /**
   * Establishes a call.
   *
   * @param isVideo indicates if a video call should be established.
   * @param isDesktopSharing indicates if a desktopSharing should be established.
   */
  private void call(boolean isVideo, boolean isDesktopSharing) {
    ChatPanel chatPanel = chatContainer.getCurrentChat();

    ChatSession chatSession = chatPanel.getChatSession();

    Class<? extends OperationSet> opSetClass;
    if (isVideo) {
      if (isDesktopSharing) opSetClass = OperationSetDesktopSharingServer.class;
      else opSetClass = OperationSetVideoTelephony.class;
    } else opSetClass = OperationSetBasicTelephony.class;

    List<ChatTransport> telTransports = null;
    if (chatSession != null) telTransports = chatSession.getTransportsForOperationSet(opSetClass);

    List<ChatTransport> contactOpSetSupported;

    contactOpSetSupported = getOperationSetForCapabilities(telTransports, opSetClass);

    List<UIContactDetail> res = new ArrayList<UIContactDetail>();
    for (ChatTransport ct : contactOpSetSupported) {
      HashMap<Class<? extends OperationSet>, ProtocolProviderService> m =
          new HashMap<Class<? extends OperationSet>, ProtocolProviderService>();
      m.put(opSetClass, ct.getProtocolProvider());

      UIContactDetailImpl d =
          new UIContactDetailImpl(
              ct.getName(), ct.getDisplayName(), null, null, null, m, null, ct.getName());
      PresenceStatus status = ct.getStatus();
      byte[] statusIconBytes = status.getStatusIcon();

      if (statusIconBytes != null && statusIconBytes.length > 0) {
        d.setStatusIcon(
            new ImageIcon(
                ImageLoader.getIndexedProtocolImage(
                    ImageUtils.getBytesInImage(statusIconBytes), ct.getProtocolProvider())));
      }

      res.add(d);
    }

    Point location = new Point(callButton.getX(), callButton.getY() + callButton.getHeight());

    SwingUtilities.convertPointToScreen(location, this);

    MetaContact metaContact = GuiActivator.getUIService().getChatContact(chatPanel);
    UIContactImpl uiContact = null;
    if (metaContact != null) uiContact = MetaContactListSource.getUIContact(metaContact);

    CallManager.call(res, uiContact, isVideo, isDesktopSharing, callButton, location);
  }
示例#8
0
  private void initSmiliesSelectorBox() {
    this.smileysBox = new SmileysSelectorBox();

    this.smileysBox.setName("smiley");
    this.smileysBox.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.INSERT_SMILEY") + " Ctrl-M");

    SIPCommMenuBar smileyMenuBar = new SIPCommMenuBar();
    smileyMenuBar.setOpaque(false);
    smileyMenuBar.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    smileyMenuBar.add(smileysBox);

    this.add(smileyMenuBar);
  }
  /**
   * Creates a new <tt>JMenuItem</tt> and adds it to this <tt>JPopupMenu</tt>.
   *
   * @param textKey the key of the internationalized string in the resources of the application
   *     which represents the text of the new <tt>JMenuItem</tt>
   * @param iconID the <tt>ImageID</tt> of the image in the resources of the application which
   *     represents the icon of the new <tt>JMenuItem</tt>
   * @param name the name of the new <tt>JMenuItem</tt>
   * @return a new <tt>JMenuItem</tt> instance which has been added to this <tt>JPopupMenu</tt>
   */
  private JMenuItem createMenuItem(String textKey, ImageID iconID, String name) {
    ResourceManagementService resources = GuiActivator.getResources();
    JMenuItem menuItem =
        new JMenuItem(
            resources.getI18NString(textKey), new ImageIcon(ImageLoader.getImage(iconID)));

    menuItem.setMnemonic(resources.getI18nMnemonic(textKey));
    menuItem.setName(name);

    menuItem.addActionListener(this);

    add(menuItem);

    return menuItem;
  }
示例#10
0
  /**
   * Implements ChatChangeListener#chatChanged(ChatPanel).
   *
   * @param chatPanel the <tt>ChatPanel</tt>, which changed
   */
  public void chatChanged(ChatPanel chatPanel) {
    if (chatPanel == null) {
      setChatSession(null);
    } else {
      MetaContact contact = GuiActivator.getUIService().getChatContact(chatPanel);

      for (PluginComponent c : pluginContainer.getPluginComponents()) c.setCurrentContact(contact);

      ChatSession chatSession = chatPanel.getChatSession();
      setChatSession(chatSession);

      leaveChatRoomButton.setEnabled(chatSession instanceof ConferenceChatSession);

      desktopSharingButton.setEnabled(!(chatSession instanceof ConferenceChatSession));

      inviteButton.setEnabled(chatPanel.findInviteChatTransport() != null);

      sendFileButton.setEnabled(chatPanel.findFileTransferChatTransport() != null);
      inviteButton.setEnabled(!chatPanel.isPrivateMessagingChat());

      if (chatSession instanceof ConferenceChatSession) {
        updateInviteContactButton();

        callButton.setVisible(false);
        callVideoButton.setVisible(false);
        callButton.setEnabled(true);
        callVideoButton.setEnabled(true);
      } else if (contact != null) {
        callButton.setVisible(true);
        callVideoButton.setVisible(true);
        new UpdateCallButtonWorker(contact).start();
      }

      changeHistoryButtonsState(chatPanel);

      setCallButtonsName();
      setCallButtonsIcons();

      currentChatTransportChanged(chatSession);
    }
  }
示例#11
0
  /**
   * Implements ChatChangeListener#chatChanged(ChatPanel).
   *
   * @param chatPanel the <tt>ChatPanel</tt>, which changed
   */
  public void chatChanged(ChatPanel chatPanel) {
    if (chatPanel == null) {
      setChatSession(null);
    } else {
      MetaContact contact = GuiActivator.getUIService().getChatContact(chatPanel);

      for (PluginComponent c : pluginContainer.getPluginComponents()) c.setCurrentContact(contact);

      setChatSession(chatPanel.chatSession);

      leaveChatRoomButton.setEnabled(chatPanel.chatSession instanceof ConferenceChatSession);

      inviteButton.setEnabled(chatPanel.findInviteChatTransport() != null);

      sendFileButton.setEnabled(chatPanel.findFileTransferChatTransport() != null);

      new UpdateCallButtonWorker(contact).start();

      changeHistoryButtonsState(chatPanel);
    }
  }
示例#12
0
  /** Initializes the chat rooms list interface. */
  private void initChatRoomList() {
    this.chatRoomsTableModel = new ChatRoomTableModel(chatRoomList);

    this.chatRoomList.addMouseListener(this);

    this.chatRoomList.setDefaultRenderer(
        ProtocolProviderService.class, new ProtocolProviderTableCellRenderer());
    this.chatRoomList.setDefaultRenderer(ChatRoomWrapper.class, new ChatRoomTableCellRenderer());

    this.chatRoomList.setOpaque(false);
    this.chatRoomList.setModel(chatRoomsTableModel);

    ConferenceChatManager confChatManager = GuiActivator.getUIService().getConferenceChatManager();

    confChatManager.addChatRoomListChangeListener(chatRoomsTableModel);

    //        this.chatRoomList.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //        this.chatRoomList.getColumnModel().getColumn(0).setMinWidth(250);
    //        this.chatRoomList.getColumnModel().getColumn(1).setMinWidth(250);
    //        this.chatRoomList.getColumnModel().getColumn(2).setPreferredWidth(50);
  }
示例#13
0
  /**
   * Handles the <tt>ActionEvent</tt>, when one of the tool bar buttons is clicked.
   *
   * @param e the <tt>ActionEvent</tt> that notified us
   */
  public void actionPerformed(ActionEvent e) {
    AbstractButton button = (AbstractButton) e.getSource();
    String buttonText = button.getName();

    ChatPanel chatPanel = chatContainer.getCurrentChat();

    if (buttonText.equals("previous")) {
      chatPanel.loadPreviousPageFromHistory();
    } else if (buttonText.equals("next")) {
      chatPanel.loadNextPageFromHistory();
    } else if (buttonText.equals("sendFile")) {
      SipCommFileChooser scfc =
          GenericFileDialog.create(
              null,
              "Send file...",
              SipCommFileChooser.LOAD_FILE_OPERATION,
              ConfigurationUtils.getSendFileLastDir());
      File selectedFile = scfc.getFileFromDialog();
      if (selectedFile != null) {
        ConfigurationUtils.setSendFileLastDir(selectedFile.getParent());
        chatContainer.getCurrentChat().sendFile(selectedFile);
      }
    } else if (buttonText.equals("history")) {
      HistoryWindow history;

      HistoryWindowManager historyWindowManager =
          GuiActivator.getUIService().getHistoryWindowManager();

      ChatSession chatSession = chatPanel.getChatSession();

      if (historyWindowManager.containsHistoryWindowForContact(chatSession.getDescriptor())) {
        history = historyWindowManager.getHistoryWindowForContact(chatSession.getDescriptor());

        if (history.getState() == JFrame.ICONIFIED) history.setState(JFrame.NORMAL);

        history.toFront();
      } else {
        history = new HistoryWindow(chatPanel.getChatSession().getDescriptor());

        history.setVisible(true);

        historyWindowManager.addHistoryWindowForContact(chatSession.getDescriptor(), history);
      }
    } else if (buttonText.equals("invite")) {
      ChatInviteDialog inviteDialog = new ChatInviteDialog(chatPanel);

      inviteDialog.setVisible(true);
    } else if (buttonText.equals("leave")) {
      ConferenceChatManager conferenceManager =
          GuiActivator.getUIService().getConferenceChatManager();
      conferenceManager.leaveChatRoom((ChatRoomWrapper) chatPanel.getChatSession().getDescriptor());
    } else if (buttonText.equals("call")) {
      call(false, false);
    } else if (buttonText.equals("callVideo")) {
      call(true, false);
    } else if (buttonText.equals("desktop")) {
      call(true, true);
    } else if (buttonText.equals("options")) {
      GuiActivator.getUIService().getConfigurationContainer().setVisible(true);
    } else if (buttonText.equals("font")) chatPanel.showFontChooserDialog();
  }
示例#14
0
  /** Initializes this component. */
  protected void init() {
    this.setLayout(new FlowLayout(FlowLayout.LEFT, 3, 0));
    this.setOpaque(false);

    this.add(inviteButton);

    // if we leave a chat room when we close the window
    // there is no need for this button
    if (!ConfigurationUtils.isLeaveChatRoomOnWindowCloseEnabled()) this.add(leaveChatRoomButton);

    this.add(callButton);
    this.add(callVideoButton);
    this.add(desktopSharingButton);
    this.add(sendFileButton);

    ChatPanel chatPanel = chatContainer.getCurrentChat();
    if (chatPanel == null || !(chatPanel.getChatSession() instanceof MetaContactChatSession))
      sendFileButton.setEnabled(false);

    this.addSeparator();

    this.add(historyButton);
    this.add(previousButton);
    this.add(nextButton);

    // We only add the options button if the property SHOW_OPTIONS_WINDOW
    // specifies so or if it's not set.
    Boolean showOptionsProp =
        GuiActivator.getConfigurationService()
            .getBoolean(ConfigurationFrame.SHOW_OPTIONS_WINDOW_PROPERTY, false);

    if (showOptionsProp.booleanValue()) {
      this.add(optionsButton);
    }

    this.addSeparator();

    if (ConfigurationUtils.isFontSupportEnabled()) {
      this.add(fontButton);
      fontButton.setName("font");
      fontButton.setToolTipText(
          GuiActivator.getResources().getI18NString("service.gui.CHANGE_FONT"));
      fontButton.addActionListener(this);
    }

    initSmiliesSelectorBox();

    this.addSeparator();

    this.inviteButton.setName("invite");
    this.inviteButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.INVITE"));

    this.leaveChatRoomButton.setName("leave");
    this.leaveChatRoomButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.LEAVE"));

    this.callButton.setName("call");
    this.callButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.CALL_CONTACT"));

    this.callVideoButton.setName("callVideo");
    this.callVideoButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.CALL_CONTACT"));

    this.desktopSharingButton.setName("desktop");
    this.desktopSharingButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.SHARE_DESKTOP_WITH_CONTACT"));

    this.historyButton.setName("history");
    this.historyButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.HISTORY") + " Ctrl-H");

    optionsButton.setName("options");
    optionsButton.setToolTipText(GuiActivator.getResources().getI18NString("service.gui.OPTIONS"));

    this.sendFileButton.setName("sendFile");
    this.sendFileButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.SEND_FILE"));

    this.previousButton.setName("previous");
    this.previousButton.setToolTipText(
        GuiActivator.getResources().getI18NString("service.gui.PREVIOUS"));

    this.nextButton.setName("next");
    this.nextButton.setToolTipText(GuiActivator.getResources().getI18NString("service.gui.NEXT"));

    inviteButton.addActionListener(this);
    leaveChatRoomButton.addActionListener(this);
    callButton.addActionListener(this);
    callVideoButton.addActionListener(this);
    desktopSharingButton.addActionListener(this);
    historyButton.addActionListener(this);
    optionsButton.addActionListener(this);
    sendFileButton.addActionListener(this);
    previousButton.addActionListener(this);
    nextButton.addActionListener(this);
  }
示例#15
0
  /**
   * Handles the <tt>ActionEvent</tt>. Determines which menu item was selected and makes the
   * appropriate operations.
   *
   * @param e the event.
   */
  public void actionPerformed(ActionEvent e) {
    JMenuItem menuItem = (JMenuItem) e.getSource();
    String itemName = menuItem.getName();

    ConferenceChatManager conferenceManager =
        GuiActivator.getUIService().getConferenceChatManager();

    if (itemName.equals("removeChatRoom")) {
      conferenceManager.removeChatRoom(chatRoomWrapper);
    } else if (itemName.equals("leaveChatRoom")) {
      conferenceManager.leaveChatRoom(chatRoomWrapper);
    } else if (itemName.equals("joinChatRoom")) {
      String nickName = null;

      nickName =
          ConfigurationManager.getChatRoomProperty(
              chatRoomWrapper.getParentProvider().getProtocolProvider(),
              chatRoomWrapper.getChatRoomID(),
              "userNickName");
      if (nickName == null) nickName = getNickname();

      if (nickName != null) conferenceManager.joinChatRoom(chatRoomWrapper, nickName, null);
      else conferenceManager.joinChatRoom(chatRoomWrapper);
    } else if (itemName.equals("openChatRoom")) {
      if (chatRoomWrapper.getChatRoom() != null) {
        if (!chatRoomWrapper.getChatRoom().isJoined()) {
          String nickName = null;

          nickName =
              ConfigurationManager.getChatRoomProperty(
                  chatRoomWrapper.getParentProvider().getProtocolProvider(),
                  chatRoomWrapper.getChatRoomID(),
                  "userNickName");
          if (nickName == null) nickName = getNickname();

          if (nickName != null) conferenceManager.joinChatRoom(chatRoomWrapper, nickName, null);
          else conferenceManager.joinChatRoom(chatRoomWrapper);
        }
      } else {
        // this is not a server persistent room we must create it
        // and join
        chatRoomWrapper =
            GuiActivator.getUIService()
                .getConferenceChatManager()
                .createChatRoom(
                    chatRoomWrapper.getChatRoomName(),
                    chatRoomWrapper.getParentProvider().getProtocolProvider(),
                    new ArrayList<String>(),
                    "",
                    false,
                    true);

        String nickName = null;

        nickName =
            ConfigurationManager.getChatRoomProperty(
                chatRoomWrapper.getParentProvider().getProtocolProvider(),
                chatRoomWrapper.getChatRoomID(),
                "userNickName");

        if (nickName == null) nickName = getNickname();

        if (nickName != null) conferenceManager.joinChatRoom(chatRoomWrapper, nickName, null);
        else conferenceManager.joinChatRoom(chatRoomWrapper);
      }

      ChatWindowManager chatWindowManager = GuiActivator.getUIService().getChatWindowManager();
      ChatPanel chatPanel = chatWindowManager.getMultiChat(chatRoomWrapper, true);

      chatWindowManager.openChat(chatPanel, true);
    } else if (itemName.equals("joinAsChatRoom")) {
      ChatRoomAuthenticationWindow authWindow = new ChatRoomAuthenticationWindow(chatRoomWrapper);

      authWindow.setVisible(true);
    } else if (itemName.equals("nickNameChatRoom")) {
      String nickName = null;

      nickName =
          ConfigurationManager.getChatRoomProperty(
              chatRoomWrapper.getParentProvider().getProtocolProvider(),
              chatRoomWrapper.getChatRoomID(),
              "userNickName");

      ChatOperationReasonDialog reasonDialog =
          new ChatOperationReasonDialog(
              GuiActivator.getResources().getI18NString("service.gui.CHANGE_NICKNAME"),
              GuiActivator.getResources().getI18NString("service.gui.CHANGE_NICKNAME_LABEL"));

      reasonDialog.setReasonFieldText(
          nickName == null
              ? chatRoomWrapper.getParentProvider().getProtocolProvider().getAccountID().getUserID()
              : nickName);

      int result = reasonDialog.showDialog();

      if (result == MessageDialog.OK_RETURN_CODE) {
        nickName = reasonDialog.getReason().trim();
      }

      ConfigurationManager.updateChatRoomProperty(
          chatRoomWrapper.getParentProvider().getProtocolProvider(),
          chatRoomWrapper.getChatRoomID(),
          "userNickName",
          nickName);
    }
  }
/**
 * The configuration window for a chat room.
 *
 * @author Yana Stamcheva
 * @author Valentin Martinet
 * @author Damian Minkov
 */
@SuppressWarnings("serial")
public class ChatRoomConfigurationWindow extends SIPCommFrame implements ActionListener {
  /** The configuration form contained in this window. */
  protected ChatRoomConfigurationForm configForm;

  /** The scroll pane contained in the "General" tab. */
  protected JScrollPane generalScrollPane = new JScrollPane();

  /** The main panel. */
  protected JPanel mainPanel = new TransparentPanel();

  /** The button that stores the data. */
  private JButton saveButton =
      new JButton(GuiActivator.getResources().getI18NString("service.gui.APPLY"));

  /** The cancel button. */
  private JButton cancelButton =
      new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

  /** The panel containing all buttons. */
  private JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));

  /** The panel containing the title. */
  private TitlePanel titlePanel = new TitlePanel();

  /** A map all configuration components. */
  protected Hashtable<String, JComponent> uiFieldsTable = new Hashtable<String, JComponent>();

  /**
   * Creates an instance of <tt>ChatRoomConfigurationWindow</tt> and initializes the configuration
   * form.
   *
   * @param chatRoomName the name of the room
   * @param configForm the configuration form to load in this configuration window
   */
  public ChatRoomConfigurationWindow(String chatRoomName, ChatRoomConfigurationForm configForm) {
    super(false);

    this.configForm = configForm;

    this.setTitle(
        GuiActivator.getResources()
            .getI18NString("service.gui.CHAT_ROOM_CONFIGURATION", new String[] {chatRoomName}));

    titlePanel.setTitleText(
        GuiActivator.getResources().getI18NString("service.gui.CHAT_ROOM_OPTIONS"));

    this.generalScrollPane.setPreferredSize(new Dimension(820, 520));
    this.generalScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    this.generalScrollPane.setOpaque(false);
    this.generalScrollPane.getViewport().setOpaque(false);

    this.mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

    this.mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    this.saveButton.addActionListener(this);
    this.cancelButton.addActionListener(this);

    this.buttonsPanel.add(saveButton);
    this.buttonsPanel.add(cancelButton);

    this.generalScrollPane.getViewport().add(mainPanel);

    this.getContentPane().add(titlePanel, BorderLayout.NORTH);
    this.getContentPane().add(generalScrollPane, BorderLayout.CENTER);
    this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);

    titlePanel.setOpaque(false);
    buttonsPanel.setOpaque(false);
    mainPanel.setOpaque(false);
    generalScrollPane.setOpaque(false);

    this.loadConfigurationForm();
  }

  /** Loads the configuration form obtained from the chat room. */
  protected void loadConfigurationForm() {
    Iterator<ChatRoomConfigurationFormField> configurationSet = configForm.getConfigurationSet();

    while (configurationSet.hasNext()) {
      ChatRoomConfigurationFormField formField = configurationSet.next();

      Iterator<?> values = formField.getValues();
      Iterator<String> options = formField.getOptions();

      JComponent field;
      JLabel label = new JLabel("", JLabel.RIGHT);

      if (formField.getLabel() != null) label.setText(formField.getLabel() + ": ");

      String fieldType = formField.getType();

      if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_BOOLEAN)) {
        // Create a check box when the field is of type boolean.
        field = new SIPCommCheckBox(formField.getLabel());
        label.setText("");

        if (values.hasNext()) {
          ((JCheckBox) field).setSelected((Boolean) values.next());
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_TEXT_FIXED)) {
        field = new JLabel();

        if (values.hasNext()) {
          String value = values.next().toString();

          ((JLabel) field).setText(value);
          field.setFont(new Font(null, Font.ITALIC, 10));
          field.setForeground(Color.GRAY);
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_LIST_MULTI)) {
        field = new TransparentPanel(new GridLayout(0, 1));

        field.setBorder(BorderFactory.createLineBorder(Color.GRAY));

        Hashtable<Object, JCheckBox> optionCheckBoxes = new Hashtable<Object, JCheckBox>();

        while (options.hasNext()) {
          Object option = options.next();
          JCheckBox checkBox = new SIPCommCheckBox(option.toString());

          field.add(checkBox);
          optionCheckBoxes.put(option, checkBox);
        }

        while (values.hasNext()) {
          Object value = values.next();

          (optionCheckBoxes.get(value)).setSelected(true);
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_LIST_SINGLE)) {
        field = new JComboBox();

        while (options.hasNext()) {
          ((JComboBox) field).addItem(options.next());
        }

        if (values.hasNext()) {
          ((JComboBox) field).setSelectedItem(values.next());
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_TEXT_MULTI)) {
        field = new JEditorPane();

        if (values.hasNext()) {
          String value = values.next().toString();

          ((JEditorPane) field).setText(value);
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_TEXT_SINGLE)
          || fieldType.equals(ChatRoomConfigurationFormField.TYPE_ID_SINGLE)) {
        field = new JTextField();

        if (values.hasNext()) {
          String value = values.next().toString();

          ((JTextField) field).setText(value);
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_TEXT_PRIVATE)) {
        field = new JPasswordField();

        if (values.hasNext()) {
          String value = values.next().toString();

          ((JPasswordField) field).setText(value);
        }
      } else if (fieldType.equals(ChatRoomConfigurationFormField.TYPE_ID_MULTI)) {
        StringBuffer buff = new StringBuffer();

        while (values.hasNext()) {
          String value = values.next().toString();
          buff.append(value);

          if (values.hasNext()) buff.append(System.getProperty("line.separator"));
        }
        field = new JTextArea(buff.toString());
      } else {
        if (label.getText() == null) continue;

        field = new JTextField();

        if (values.hasNext()) {
          String value = values.next().toString();

          ((JTextField) field).setText(value);
        }
      }

      // If the field is not fixed (i.e. could be changed) we would like
      // to save it in a list in order to use it later when user saves
      // the configuration data.
      if (!fieldType.equals(ChatRoomConfigurationFormField.TYPE_TEXT_FIXED)) {
        uiFieldsTable.put(formField.getName(), field);
      }

      JPanel fieldPanel = new TransparentPanel(new GridLayout(1, 2));
      fieldPanel.setOpaque(false);

      if (!(field instanceof JLabel))
        fieldPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0));
      else fieldPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 1, 0));

      fieldPanel.add(label);
      fieldPanel.add(field);

      this.mainPanel.add(fieldPanel);
    }
  }

  /**
   * Computes the maximum width of a label in the configuration form.
   *
   * @param configForm the configuration form containing all labels.
   * @return the maximum width of a label in the configuration form
   */
  private int computeLabelWidth(ChatRoomConfigurationForm configForm) {
    int labelWidth = 0;

    Iterator<ChatRoomConfigurationFormField> configurationSet = configForm.getConfigurationSet();

    while (configurationSet.hasNext()) {
      ChatRoomConfigurationFormField formField = configurationSet.next();

      if (formField.getLabel() == null) continue;

      JLabel label = new JLabel(formField.getLabel());

      int newLabelWidth =
          SwingUtilities.computeStringWidth(
              label.getFontMetrics(label.getFont()), formField.getLabel());

      if (newLabelWidth > labelWidth) labelWidth = newLabelWidth;
    }

    // We add 10 pixels to be sure that even after adding the ':' char
    // the label will rest visible.
    return labelWidth + 10;
  }

  /**
   * Saves all configuration settings when the "Save" button is pressed.
   *
   * @param e the <tt>ActionEvent</tt> that notified us of the button action
   */
  public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();

    if (button.equals(saveButton)) {
      Iterator<ChatRoomConfigurationFormField> configurationSet = configForm.getConfigurationSet();

      while (configurationSet.hasNext()) {
        ChatRoomConfigurationFormField formField = configurationSet.next();

        // If the field is of type fixed the user could not change it,
        // so we skip it.
        if (formField.getType().equals(ChatRoomConfigurationFormField.TYPE_TEXT_FIXED)) continue;

        JComponent c = uiFieldsTable.get(formField.getName());

        if (c instanceof JTextComponent) {
          String newValue = ((JTextComponent) c).getText();

          if (formField.getType().equals(ChatRoomConfigurationFormField.TYPE_ID_MULTI)) {
            // extract values
            StringTokenizer idTokens =
                new StringTokenizer(newValue, System.getProperty("line.separator"));
            while (idTokens.hasMoreTokens()) {
              formField.addValue(idTokens.nextToken());
            }
          } else formField.addValue(newValue);
        } else if (c instanceof AbstractButton) {
          boolean isSelected = ((AbstractButton) c).isSelected();

          formField.addValue(isSelected);
        } else if (c instanceof JComboBox) {
          Object selectedObject = ((JComboBox) c).getSelectedItem();

          formField.addValue(selectedObject);
        } else if (c instanceof JPanel) {
          Component[] components = c.getComponents();

          for (Component comp : components) {
            if (!(comp instanceof JCheckBox)) continue;

            JCheckBox checkBox = (JCheckBox) comp;

            formField.addValue(checkBox.getText());
          }
        }
      }

      new Thread() {
        @Override
        public void run() {
          try {
            configForm.submit();
          } catch (Exception e) {
            new ErrorDialog(
                    ChatRoomConfigurationWindow.this,
                    GuiActivator.getResources().getI18NString("service.gui.ERROR"),
                    GuiActivator.getResources()
                        .getI18NString("service.gui.CHAT_ROOM_CONFIGURATION_SUBMIT_FAILED"),
                    e)
                .showDialog();
          }
        }
      }.start();
    }

    this.dispose();
  }

  @Override
  protected void close(boolean isEscaped) {
    this.dispose();
  }

  /**
   * Overwrites the setVisible method in order to set the position of this window before showing it.
   *
   * @param isVisible indicates if this frame should be visible
   */
  @Override
  public void setVisible(boolean isVisible) {
    if (isVisible) setLocationRelativeTo(null);

    super.setVisible(isVisible);
  }
}