/*******************************************************************************
 * 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.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

import lu.tudor.santec.gecamed.core.gui.MainFrame;

import org.apache.log4j.Logger;

/**
 * JButton that displays the memory usage of the Java VM
 * as a Bargraph. A Tooltip provides additional information
 * about the free, used and allocated RAM.
 * If The button is clicked, the Garbage collection is called.
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @Version
 * <br>$Log: MemoryMonitorButton.java,v $
 * <br>Revision 1.7  2013-12-27 18:07:52  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.6  2013-07-15 06:18:34  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.5  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.4  2008-01-15 09:29:38  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 * <br>Revision 1.3  2007-12-17 14:59:59  heinemann
 * <br>plugins and file store and open
 * <br>
 * <br>Revision 1.2  2007-12-06 14:46:44  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class MemoryMonitorButton extends JButton implements ActionListener {

	private static final long serialVersionUID = 3030537064914356613L;
	
	private static Logger logger = Logger.getLogger(
			MemoryMonitorButton.class.getName());
	
	private Runtime rt = Runtime.getRuntime();
	private NumberFormat nf = NumberFormat.getNumberInstance();
	private boolean drawLeds;
	private static final int SIZE = 32;
	private static final int BAR_WITH = 8;
	private static final int OFFSET = 5;
	private static final Color USED = Color.RED;
	private static final Color ALLOC = Color.YELLOW;
	private static final Color FREE = Color.GREEN;
	private static final int LEDSPAN = 1;
	private static final int LEDSIZE = 2;
	
	/**
	 * Creates a new Button.
	 * @param enabled enable the Garbage Collection on click.
	 * @param drawLeds draw LED-like bargraph
	 */
	public MemoryMonitorButton(boolean enabled, boolean drawLeds) {
            this.setEnabled(enabled);
            this.setFocusPainted(false);
            this.drawLeds = drawLeds;
		nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
        try {
        	this.setIcon(new ImageIcon(MainFrame.class.getResource("resources/icons/empty_32.png")));	
		} catch (Exception e) {
			logger.warn("Icon for memory button missing");
		}
		this.setSize(40,40);
		this.addActionListener(this);
		new Thread() {
			public void run() {
				while(true) {	
				try {
					repaint();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				}
			}
		}.start();
	}
	
	
	
	/* (non-Javadoc)
	 * @see java.awt.Component#paint(java.awt.Graphics)
	 */
	public void paint(Graphics g) {
		super.paint(g);
		
		double maxVM = (rt.maxMemory()/1024);	 
		double totalAlloc = (rt.totalMemory()/1024);	
		double freeAlloc = (rt.freeMemory()/1024);
		double used = totalAlloc - freeAlloc;
		double free = maxVM - used;

		if (this.drawLeds) {
		this.drawLeds(g ,used, totalAlloc, maxVM);
		} else {
			drawBar(g ,used, totalAlloc, maxVM);
		}
		
		this.setToolTipText("<html><h2>&nbsp;&nbsp; Memory Status: &nbsp;&nbsp;</h2>"+
				"<b>&nbsp;&nbsp; Max: </b>"+ nf.format(maxVM/1024) + " mb<br>" +
				"<b>&nbsp;&nbsp; Allocated: </b>"+ nf.format(totalAlloc/1024) + " mb<br>" +
				"<b>&nbsp;&nbsp; Used: </b>"+ nf.format(used/1024) + " mb<br>" +
				"<b>&nbsp;&nbsp; Free: </b>"+ nf.format(free/1024) + " mb<br>&nbsp;" );
	}

	/**
	 * Just for testing purpose...
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame jf = new JFrame();
		jf.add(new MemoryMonitorButton(true, true));
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}



	public void actionPerformed(ActionEvent e) {
		logger.info("Running GC!");
		System.gc();
	}
	
	private void drawBar(Graphics g, double used, double totalAlloc, double maxVM) {
		int usedDraw = (int) ((used/maxVM)*30);
		int allocDraw = (int) ((totalAlloc/maxVM)*30);

		g.setColor(Color.BLACK);
		g.setFont(new Font("SansSerif",Font.PLAIN,10));
		g.drawString("Mem",OFFSET+ BAR_WITH +2, OFFSET + 13);
		g.drawString("Info",OFFSET+ BAR_WITH +2, OFFSET+ 28);
		
		g.setColor(FREE);
		g.fillRect(OFFSET,OFFSET,BAR_WITH,SIZE-1);
		g.setColor(ALLOC);
		g.fillRect(OFFSET,SIZE-allocDraw+OFFSET,BAR_WITH,allocDraw);
		g.setColor(USED);
		g.fillRect(OFFSET,SIZE-usedDraw+OFFSET,BAR_WITH,usedDraw);
	}
	
	private void drawLeds(Graphics g, double used, double totalAlloc, double maxVM) {
		
		int usedDraw = SIZE -(int) ((used/maxVM)*30);
		int allocDraw = SIZE -(int) ((totalAlloc/maxVM)*30);

		g.setColor(Color.BLACK);
		g.setFont(new Font("SansSerif",Font.PLAIN,10));
		g.drawString("Mem",OFFSET+ BAR_WITH +2, OFFSET + 13);
		g.drawString("Info",OFFSET+ BAR_WITH +2, OFFSET+ 28);
		
		g.setColor(FREE);		
		for (int i = 0; i <=SIZE; i+=(LEDSIZE+LEDSPAN)){
			if (OFFSET+i >= allocDraw) {
				g.setColor(ALLOC);		
			}
			if (OFFSET+i >= usedDraw) {
				g.setColor(USED);		
			}
			g.fillRect(OFFSET,OFFSET+i,BAR_WITH, LEDSIZE);
		}
		
		
	}
	
}
