/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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 along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.core.gui.widgets;

import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableModel;

import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.GecamedUser;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.UserMessage;

/**
 * MessageTabelModel to handle and display the arrived messages
 * class MessageTableModel has replace the class ListModel
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 * 
 * @version
 * <br>$Log: MessageTableModel.java,v $
 * <br>Revision 1.4  2013-02-20 09:50:29  kutscheid
 * <br>prevent possible NullPointerExceptions
 * <br>
 * <br>Revision 1.3  2013-02-19 12:07:34  ferring
 * <br>GECAMedLists changed. Will now automatically load list of all beans
 * <br>
 * <br>Revision 1.2  2011-11-15 08:59:17  ferring
 * <br>Exceptions prevented
 * <br>
 * <br>Revision 1.1  2010-02-09 13:29:17  troth
 * <br>Create MessageTableModel to handle and display the arrived messages (class MessageTableModel has replace the class ListModel)
 * <br>
 */

public class MessageTableModel extends DefaultTableModel {
	
	private static final long serialVersionUID = 1L;
	
	private Vector<UserMessage> userMessages = new Vector<UserMessage>();
	
	private HashMap<Integer, String> usernameHash = new HashMap<Integer, String>();
	
	public MessageTableModel() {
		super();
		updateUserList();
		
		// add listener to be update the user list  
		GECAMedLists.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				updateUserList();
			}
		}, GecamedUser.class);
	}
	
	
	/**
	 * update the user list
	 */
	private void updateUserList() {
		
		GecamedUser[] users = null;
		
//		if (GECAMedLists.getArray(GecamedUser.class) == null) {
//			try {
//				Collection usersCol = ((UserAdminInterface) ManagerFactory.getRemote(UserAdminBean.class)).getUserList();
//				users = (GecamedUser[]) usersCol.toArray(new GecamedUser[0]);
//				GECAMedLists.storeList(GecamedUser.class, users);
//			} catch (FinderException e) {
//				e.printStackTrace();
//			}
//		} else {
			users = GECAMedLists.getArray(GecamedUser.class);				
//		}
			
		if (users != null) {
			for (int i = 0; i < users.length; i++) {
				usernameHash.put(users[i].getId(), users[i].getLogin());
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.swing.table.AbstractTableModel#getColumnClass(int)
	 */
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		switch (columnIndex) {
	
		case 0:
		case 2:
		case 3:
			return ImageIcon.class;
		case 1:
			return JLabel.class;
		default:
			return super.getColumnClass(columnIndex);
		}
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#getColumnCount()
	 */
	public int getColumnCount() {
		return 4;
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#getRowCount()
	 */
	public int getRowCount() {	
		if(userMessages == null)
			return 1;
		else
			return userMessages.size();
	}
	
	/* (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#isCellEditable(int, int)
	 */
	@Override
	public boolean isCellEditable(int row, int column) {
		return false;
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#getValueAt(int, int)
	 */
	public Object getValueAt(int row, int col) {
		
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
		
		UserMessage userMessage = userMessages.get(row);
					
		switch (col) {
		// column 0: the imageicon how show the importance of the message
		case 0:
			if(userMessage.getIsImportant())
				return (ImageIcon) getScaledIcon(GECAMedIconNames.URGENT, 20);
			else
				return (ImageIcon) getScaledIcon(GECAMedIconNames.MESSAGE_NEW, 20);
		// column 1: the text of the message
		case 1:
			return "<html><b>" + df.format((Date) userMessage.getDate()) + " " + usernameHash.get(userMessage.getSenderId()) + " -> " +
			(userMessage.getAllUser()?"ALL": usernameHash.get(userMessage.getReceiverId())) + 
			"</b><p style=\"font-family:Arial;font-size:10;font-weight:normal\">" + 
			(userMessage.getMessage()!=null?userMessage.getMessage().replaceAll("\n", "<br>"):"") + "</p></html>";
		// column 2: the imageicon how marks a message if it is read or not read	
		case 2:
			if(userMessage.getIsRead())
				return (ImageIcon) getScaledIcon(GECAMedIconNames.MESSAGE_GREY, 20);
			else
				return (ImageIcon) getScaledIcon(GECAMedIconNames.MESSAGE, 20);
		// column 3: the imageicon of the trash to delete a message
		case 3:
			return (ImageIcon) getScaledIcon(GECAMedIconNames.MESSAGE_DELETE, 20);

		default:
			return "leer";
		}
	}
	
	/**
	 * add a usermessage to the tablemodel
	 * 
	 * @param usermessage the usermessage to be add
	 */
	public void addMessage(UserMessage userMessage) {
		this.userMessages.add(0,userMessage);
		this.fireTableDataChanged();
	}
	
	/**
	 * returns a usermessage object specified by row
	 * 
	 * @param row the specified row of the message
	 * @return a usermessage Object
	 */
	public Object getMessageAt(int row) {
		if (row < userMessages.size())
			 return (UserMessage) this.userMessages.get(row);
		else return null;
	}
	
	/**
	 * remove a message form the tablemodel
	 * 
	 * @param row the row (in the table) of the message to be removed
	 */
	public void removeMessage(int row) {
		if (row < userMessages.size())
			this.userMessages.remove(row);
	}
	
	/**
	 * removes all message form the tablemodel
	 */
	public void removeAllMessage() {
		this.userMessages.clear();
	}
	
	/**
	 * returns a scaled imageicon
	 * 
	 * @param iconName the name of the icon to be scaled
	 * @param size the size to scaled
	 * @return a imageicon the scaled imageicon
	 */
	public static ImageIcon getScaledIcon(String iconName, int size) {
		return new ImageIcon(GECAMedModule.getIcon(iconName).getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH));
	}

}
