/*******************************************************************************
 * 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.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.UserMessage;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.beans.LoginBean;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.beans.UserMessageManager;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.UserMessageInterface;
import lu.tudor.santec.i18n.Translatrix;

/**
 * Label that shows new incomming messages from other GECAMed Users.
 * the label is placed in the statusbar on the bottom of the client window.
 * If the Label is clicked it opens a Popup with a message history.
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @Version
 * <br>$Log: MessageLabel.java,v $
 * <br>Revision 1.10  2013-12-27 18:07:52  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.9  2010-02-09 13:29:52  troth
 * <br>add and implement methods to load, save, delete and display messagelabels
 * <br>
 * <br>Revision 1.8  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.7  2008-01-15 09:29:38  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 * <br>Revision 1.6  2007-12-06 14:46:44  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class MessageLabel extends JLabel implements MouseListener {

	private static final long serialVersionUID = 1L;
	
	private JPanel messagePanel;
	
	private JTable messageTable;

	private Popup popup;

	private JScrollPane jsp;

	private MessageTableModel messageTableModel;

	private JLabel closeButton;

	private boolean isShowing;
	
	/**
	 * creates a new instacne of the messagelabel
	 */
	public MessageLabel() {
        this.setBorder(new EmptyBorder(0,3,0,3));
        this.setOpaque(true);
        this.addMouseListener(this);
        
        this.messagePanel = new JPanel(new BorderLayout());
        this.messagePanel.setBackground(Color.WHITE);
        this.messagePanel.setBorder(new TitledBorder(""));
        
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setOpaque(false);
        topPanel.add(new JLabel(Translatrix.getTranslationString("core.messages")), BorderLayout.CENTER);
        this.closeButton = new JLabel(GECAMedModule.getScaledIcon(GECAMedIconNames.CLOSE, 10));
        this.closeButton.addMouseListener(this);
        topPanel.add(this.closeButton, BorderLayout.EAST);
        messagePanel.add(topPanel, BorderLayout.NORTH);
        this.messagePanel.setPreferredSize(new Dimension(400,300));

        this.messageTableModel = new MessageTableModel();
        this.messageTable = new JTable(messageTableModel);
        this.messageTable.addMouseListener(this);
        this.messageTable.setTableHeader(null);
        this.messageTable.setShowVerticalLines(false);
        this.messageTable.setIntercellSpacing(new Dimension(0, 0));
        this.messageTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.messageTable.setRowSelectionAllowed(true);
        this.messageTable.getColumn(this.messageTable.getColumnName(0)).setMinWidth(40);
        this.messageTable.getColumn(this.messageTable.getColumnName(0)).setMaxWidth(40);
        this.messageTable.getColumn(this.messageTable.getColumnName(2)).setMinWidth(40);
        this.messageTable.getColumn(this.messageTable.getColumnName(2)).setMaxWidth(40);
        this.messageTable.getColumn(this.messageTable.getColumnName(3)).setMinWidth(40);
        this.messageTable.getColumn(this.messageTable.getColumnName(3)).setMaxWidth(40);
        this.messageTable.setRowHeight(70);
        
        jsp = new JScrollPane(this.messageTable);
        jsp.setOpaque(false);
        jsp.getViewport().setOpaque(false);
        jsp.addMouseListener(this);
        this.messagePanel.add(jsp, BorderLayout.CENTER);
        this.loadMessages();
	}
	
    
    /**
     * set the icon and the text of the label of the new message
     */
    private synchronized void newMessages() {
    	if (getNewMessageCount() != 0) {
			
    		this.setIcon(GECAMedModule.getMiniIcon(GECAMedIconNames.MESSAGE));
			this.setForeground(Color.BLACK);
			if (messageTableModel.getRowCount() > 1) {
				this.setText(getNewMessageCount() + " " + Translatrix.getTranslationString("core.message.newMessages") + " ! / " + messageTableModel.getRowCount());				
			} else {
				this.setText(getNewMessageCount() + " " + Translatrix.getTranslationString("core.message.newMessage") + " ! / " + messageTableModel.getRowCount());
			}
		} else {
			this.setIcon(GECAMedModule.getMiniIcon(GECAMedIconNames.MESSAGE_GREY));
			this.setForeground(Color.LIGHT_GRAY.darker());
			
			if (messageTableModel.getRowCount() > 1) {
				this.setText(messageTableModel.getRowCount() + " " + Translatrix.getTranslationString("core.messages"));				
			} else {
				this.setText(messageTableModel.getRowCount() + " " + Translatrix.getTranslationString("core.message"));
			}
		}
		this.validate();
	}

	/* (non-Javadoc)
	 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
	 */
	public void mouseClicked(MouseEvent e) {
		
		if (e.getSource().equals(this)) {
			// hide popup if showing
			if (isShowing) {
				popup.hide();
				isShowing=false;
				return;
			}
			// show the popup with message history
			PopupFactory factory = PopupFactory.getSharedInstance();
			popup = factory.getPopup(this, this.messagePanel, 
					(int)this.getLocationOnScreen().getX(), 
					(int)(this.getLocationOnScreen().getY()-300));
			isShowing = true;
			popup.show();
			this.newMessages();
			
		// show messagebox	
		} else if (e.getSource().equals(this.messageTable) && e.getClickCount() >= 2) {
			// create a reply to the selected message
			if (this.messageTable.getSelectedColumn() == 1) {
				UserMessage um = (UserMessage) this.messageTableModel.getMessageAt(this.messageTable.getSelectedRow());
				//UserMessage
				String oldText = ""; 
				oldText = ">" + um.getMessage().replaceAll("\n", "\n>") + "\n";
				MessageSendDialog.showDialog("id" + um.getSenderId(), oldText);
			}
		} else if (e.getSource().equals(this.messageTable) && e.getClickCount() >=1) {
			// create a reply to the selected message
			if (this.messageTable.getSelectedColumn() == 2) {
				updateMessage(this.messageTable.getSelectedRow());
			}else if (this.messageTable.getSelectedColumn() == 3) {
				deleteMessage(this.messageTable.getSelectedRow());
			}
		} else if (e.getSource().equals(this.closeButton)) {
			// hide popup 
			popup.hide();
			isShowing=false;
		} 
	}

	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
    
	/**
	 * load Messages form the database into the label
	 * 
	 */
	public void loadMessages() {
		
		UserMessageInterface userMessageInterface = (UserMessageInterface) ManagerFactory.getRemote(UserMessageManager.class);
		LoginInterface loginInterface = (LoginInterface) ManagerFactory.getRemote(LoginBean.class);
		
		Collection<UserMessage> messages =  userMessageInterface.getUserMessage(loginInterface.getCurrentUserID());
		
		messageTableModel.removeAllMessage();
		
		for (UserMessage userMessage : messages)
			this.messageTableModel.addMessage(userMessage);
		this.newMessages();
	}
	
	/**
	 * update the message read status in the messagetable and the database
	 * @param selectedRow
	 */
	private void updateMessage(int selectedRow) {
		UserMessageInterface userMessageInterface = (UserMessageInterface) ManagerFactory.getRemote(UserMessageManager.class);
		UserMessage userMessage = (UserMessage) messageTableModel.getMessageAt(selectedRow);
		userMessage.setIsRead(!userMessage.getIsRead());
		userMessageInterface.saveUserMessage(userMessage);
		this.loadMessages();
	}
	
	/**
	 * detete message in the messagetable and the database 
	 * @param selectedRow
	 */
	public void deleteMessage(int selectedRow) {
		UserMessageInterface userMessageInterface = (UserMessageInterface) ManagerFactory.getRemote(UserMessageManager.class);
		UserMessage userMessage = (UserMessage) messageTableModel.getMessageAt(selectedRow);
		userMessageInterface.deleteUserMessage(userMessage);
		messageTableModel.removeMessage(selectedRow);
		this.loadMessages();
	}
	
	/**
	 * repaint the Popup with a the messages
	 */
	public void repaintMessageTable(){ 
		this.loadMessages();
		try {
			popup.show();			
		} catch (Throwable e) {}
	}
	
	/**
	 * count the new messages of the user how is login
	 * 
	 * @return a int the Count of the new messeages 
	 */
	public int getNewMessageCount(){
		UserMessageInterface userMessageInterface = (UserMessageInterface) ManagerFactory.getRemote(UserMessageManager.class);
		LoginInterface loginInterface = (LoginInterface) ManagerFactory.getRemote(LoginBean.class);
		
		Collection<UserMessage> messages =  userMessageInterface.getUserMessage(loginInterface.getCurrentUserID());
		
		int count = 0;
		for (UserMessage userMessage : messages)
			if(!userMessage.getIsRead()) count++;
		return count;
	}
}

