/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.core.gui.widgets;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.border.TitledBorder;

import lu.tudor.santec.gecamed.core.ejb.session.beans.MessageSenderBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.MessageSenderInterface;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.GecamedUser;
import lu.tudor.santec.i18n.Translatrix;

import com.jgoodies.forms.builder.ButtonBarBuilder;

/**
 * Dialog to send text messages to other gecamed users via JMS
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 * 
 * @Version <br>
 *          $Log: MessageSendDialog.java,v $
 *          Revision 1.13  2013-04-05 12:05:56  ferring
 *          scrollpane added to message dialog
 *
 *          Revision 1.12  2010-02-09 13:28:03  troth
 *          add class ComboBoxRenderer to render user objects in the combobox of the messageSenderDialog
 * <br>
 *          Revision 1.11 2009-02-04 10:15:56 hermen <br>
 *          added functionality to get all Users that are logged in on a GECAMed
 *          Server <br>
 * <br>
 *          Revision 1.10 2008-09-25 09:43:06 heinemann <br>
 *          fixed copyrights <br>
 * <br>
 *          Revision 1.9 2008-01-15 09:29:38 hermen <br>
 *          updated Javadoc and refactured code <br>
 * <br>
 *          Revision 1.8 2007-12-06 14:46:44 hermen <br>
 *          updated Javadoc and refactured code <br>
 * 
 */
public class MessageSendDialog extends JDialog implements ActionListener {
	// ~ Static fields/initializers
	// =============================================

	private static final long serialVersionUID = 1L;

	// ~ Instance fields
	// ========================================================

	private JButton sendButton;
	private static JTextArea messageField;

	private MessageSenderInterface messageSender;

	private JButton cancelButton;

	private JComboBox cb;

	private JCheckBox important;

	public static MessageSendDialog messageSenderDialog;

	// ~ Constructors
	// ===========================================================

	/**
	 * creates a dialog to send text messages
	 */
	private MessageSendDialog() {
		super(MainFrame.getInstance());

		this.setTitle(Translatrix.getTranslationString("core.sendMessage"));

		this.getContentPane().setLayout(new BorderLayout());
		this.getContentPane().setBackground(Color.WHITE);

		JPanel sendToPanel = new JPanel(new BorderLayout());
		sendToPanel.setOpaque(false);

		String[] logins = { MessageSenderInterface.ALL_USERS };
		try {
			String s = MessageSenderInterface.ALL_USERS + ","
					+ System.getProperties().getProperty("validUsers");
			logins = s.split(",");
		} catch (Exception e) {

		}

		cb = new JComboBox(logins);

		cb.setBorder(new TitledBorder(Translatrix
				.getTranslationString("core.sendTo")));

		// Add renderer to the combobox to display each item in its menu
		ComboBoxRenderer renderer = new ComboBoxRenderer();
		cb.setRenderer(renderer);
		sendToPanel.add(cb, BorderLayout.CENTER);

		important = new JCheckBox(Translatrix
				.getTranslationString("core.important"));
		important.setOpaque(false);
		sendToPanel.add(important, BorderLayout.EAST);

		messageField = new JTextArea(10, 30);
		messageField.setLineWrap(true);
		messageField.setBorder(new TitledBorder(Translatrix
				.getTranslationString("core.message")));
		
		JScrollPane	scroller	= new JScrollPane(messageField);
		scroller.getViewport().setOpaque(false);
		scroller.setOpaque(false);

		ButtonBarBuilder bb = new ButtonBarBuilder();
		bb.addGlue();

		cancelButton = new JButton(Translatrix
				.getTranslationString("core.cancel"), GECAMedModule
				.getSmallIcon(GECAMedIconNames.CANCEL));
		bb.addGridded(cancelButton);
		cancelButton.addActionListener(this);
		sendButton = new JButton(Translatrix.getTranslationString("core.send"),
				GECAMedModule.getSmallIcon(GECAMedIconNames.MESSAGE));
		bb.addGridded(sendButton);
		sendButton.addActionListener(this);

		this.getContentPane().add(sendToPanel, BorderLayout.NORTH);
		this.getContentPane().add(scroller, BorderLayout.CENTER);
		JPanel buttonPanel = bb.getPanel();
		buttonPanel.setOpaque(false);
		this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);

		this.pack();

		try {
			InitialContext ctx = new InitialContext();
			this.messageSender = (MessageSenderInterface) ManagerFactory
					.getRemote(MessageSenderBean.class);
			ctx.close();
		} catch (NamingException e) {
			MainFrame.reportServerError(e);
		}
	}

	/**
	 * returns a static instance of a MessageSendDialog
	 * 
	 * @return
	 */
	public static MessageSendDialog getInstance() {
		if (messageSenderDialog == null) {
			messageSenderDialog = new MessageSendDialog();
		}
		return messageSenderDialog;
	}

	// ~ Methods
	// ================================================================

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(this.sendButton)) {
			try {
				String s = cb.getSelectedItem().toString();
				s = s.replace(" | online", "");
				s = s.replace(" | offline", "");
				// send the message
				MessageSendDialog.this.messageSender.sendTextMessage(
						messageField.getText(), s, important.isSelected());
			} catch (Exception ex) {
				MainFrame.reportServerError(ex);
			}
		}
		this.setVisible(false);
	}

	/**
	 * set the selected message receiver of the dialog used to create replies to
	 * other messages
	 * 
	 * @param receiver
	 */
	public void setReceiver(String receiver) {
		try {
			this.cb.setSelectedItem(receiver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * shows the Dialog
	 */
	public static void showDialog() {
		showDialog(null, null);
	}

	/**
	 * shows the Dialog centered on the Screen.
	 * 
	 * @param receiver
	 *            who sould get the message (gecamed user)
	 * @param txt
	 *            message text
	 */
	public static void showDialog(String receiver, String txt) {
		if (messageSenderDialog == null) {
			messageSenderDialog = new MessageSendDialog();
		}
		if (receiver != null) {
			messageSenderDialog.setReceiver(receiver);
		}
		// reset the text
		if (txt == null) {
			messageField.setText("");
		} else {
			messageField.setText(txt);
		}

		
		messageSenderDialog.cb.removeAllItems();
		messageSenderDialog.cb.addItem(MessageSenderInterface.ALL_USERS);
		
		// ---------------------------------------------------------
		// Get all user in the combobox and mark user how are online
		Collection<GecamedUser> usersLogin = MainFrame.getInstance().login
				.getOnlineUsers(null);
		Collection<GecamedUser> users = MainFrame.getInstance().login
				.getAllUsers();
				
		Boolean userOnline = false;
		String[] userOfflineArray = new String[users.size()];
		int i = 0;
		int userOnlineCount = 0;
		
		if (users != null) {
			for (GecamedUser gecamedUser : users) {
				for (GecamedUser gecamedUserLogin : usersLogin) {

					if (((String) gecamedUser.getLogin())
							.equals(((String) gecamedUserLogin.getLogin()))) {
						userOnline = true;
						userOnlineCount++;
						break;
					}
				}
				if(userOnline)
					messageSenderDialog.cb.addItem(gecamedUser.getLogin() + " | online");
				else{
					userOfflineArray[i] = (String) gecamedUser.getLogin() + " | offline";
					i++;
				}
				userOnline = false;
			}
		}
		for(i=0;i<(userOfflineArray.length-userOnlineCount);i++) messageSenderDialog.cb.addItem((String) userOfflineArray[i]);
		// ---------------------------------------------------------
		
		MainFrame.showDialogCentered(MessageSendDialog.getInstance());
		messageField.requestFocus();
	}

	/**
	 * renderer for the user objects in the combobox of the messageSenderDialog.
	 *
	 * @author Thorsten Roth thorsten.roth(at)tudor.lu
	 *
	 * @version
	 * <br>$Log: MessageSendDialog.java,v $
	 * <br>Revision 1.13  2013-04-05 12:05:56  ferring
	 * <br>scrollpane added to message dialog
	 * <br>
	 * <br>Revision 1.12  2010-02-09 13:28:03  troth
	 * <br>add class ComboBoxRenderer to render user objects in the combobox of the messageSenderDialog
	 * <br>
	 */
	class ComboBoxRenderer extends JLabel implements ListCellRenderer { 
		private static final long serialVersionUID = 1L;
		private Color onlineColor = new Color(58, 192, 106);
		private Color offlineColor = new Color(230, 63, 63);
		private String selectedString;

		public ComboBoxRenderer() {
			setOpaque(true);
			setHorizontalAlignment(LEFT);
			setVerticalAlignment(CENTER);
		}

		/* (non-Javadoc)
		 * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
		 * 
		 * This method finds the text corresponding to the selected value and returns the label. 
		 */
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			if (isSelected) {
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			} else {
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}

			selectedString = ((String) value.toString());
			setText(selectedString);

			if (selectedString.contains(" | online"))
				setForeground(onlineColor);
			else
				setForeground(offlineColor);

			if (selectedString.equals("ALL"))
				setForeground(Color.BLACK);

			return this;
		}
	}
}
