// file:$ISIP_IFC/util/demo/isip_comm_client_speaker_verification/DataMonitor.java
// version: $Id: DataMonitor.java 10572 2006-06-26 21:54:34Z rei5 $

/*
 * @(#)DataMonitor.java	1.26 99/04/23
 *
 * Copyright (c) 1998, 1999 by Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

// import necessary java libraries
//
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;


/**
 * Tracks Volume allocated & used, displayed in graph form.
 */
public class DataMonitor extends JPanel {

    //-------------------------------------------------------------------------
    //
    // public methods
    //
    //-------------------------------------------------------------------------
    public static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
    public Surface surf;
    public JPanel controls;
    public boolean doControls;
    public JTextField tf;
    
    /**
     * Constructor of the class
     */
    public DataMonitor() {
        setLayout(new BorderLayout());
        add(surf = new Surface());
        controls = new JPanel();
	Font font = new Font("Ariel", Font.BOLD, 18);
        JLabel label = new JLabel("Sample Rate");
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(label);
        tf = new JTextField("300");
	controls.add(tf);
        controls.add(label = new JLabel("ms"));
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(dateStampCB);
        dateStampCB.setFont(font);
        addMouseListener(new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
		    removeAll();
		    if ((doControls = !doControls)) {
			surf.stop();
			add(controls);
		    } 
		    else {
			try {
			    surf.sleepAmount = Long.parseLong(tf.getText().trim());
			} catch (Exception ex) {}
			surf.start();
			add(surf);
		    }
		    validate();
		    repaint();
		}
	    });
    }
    
    
    /**
     * a runnable class
     */
    public class Surface extends JPanel implements Runnable {

	// public members
	//
        public Thread thread;
        public int pts_all[];
        public long sleepAmount = 50;
	public int max_points = 0;
	public int MAX_POINTS = 50000;
	public int position = 0;
	public int pts_received = 0;
        
	// private members
	//
	private int w, h;
        private BufferedImage bimg;
        private Graphics2D big;
        private Font font = new Font("Ariel", Font.BOLD, 16);
        private Runtime r = Runtime.getRuntime();
        private int columnInc;
        private int pts[];
        private int ptNum;
        private int ascent, descent;
        private float freeVolume, totalVolume;
        private Rectangle graphOutlineRect = new Rectangle();
        private Rectangle2D mfRect = new Rectangle2D.Float();
        private Rectangle2D muRect = new Rectangle2D.Float();
        private Line2D graphLine = new Line2D.Float();
        private Color graphColor = new Color(46, 139, 87);
        private Color mfColor = new Color(0, 100, 0);
        private String usedStr;
	private int flag = 0;


	/**
	 * constructor for the class
	 */
        public Surface() {
            setBackground(Color.white);
            addMouseListener(new MouseAdapter() {
		    public void mouseClicked(MouseEvent e) {
			if (thread == null) start(); else stop();
		    }
		});
	    pts_all = new int[MAX_POINTS];
	
	    for (int i = 0; i < MAX_POINTS; i++)
		pts_all[i] = 0;
        }
	
	/**
	 * get minimum size
	 */
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }
	
	 /**
	  *get a maximum size
	  */
        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
	
	/**
	 * get preferred size
	 */
        public Dimension getPreferredSize() {
            return new Dimension(70,255);
        }

	/**
	 * paint method
	 */
        public void paint(Graphics g) {
	    
            if (big == null) {
                return;
            }
	    
            big.setBackground(getBackground());
            big.clearRect(0,0,w,h);

	    float freeVolume;
	    freeVolume =  (float)((300-pts_all[0]));
	    float totalVolume = (float)(300.0);

            // .. Draw allocated and used strings ..
	    //
            big.setColor(Color.black);
	    
	    big.drawString(String.valueOf((int) totalVolume) + 
			   " sec",  2.0f, (float) ascent-0.9f);

            usedStr = " " + String.valueOf(((int) (totalVolume- freeVolume))) + " sec";
	    big.drawString(usedStr, 2, h-descent);

            // Calculate remaining size
	    //
            float ssH = ascent + descent;
            float remainingHeight = (float) (h - (ssH*2) - 0.5f);
            float blockHeight = remainingHeight/10;
            float blockWidth = 20.0f;
            float remainingWidth = (float) (w - blockWidth);

            // .. Volume Free ..
            //
	    big.setColor(mfColor);
            int MemUsage = (int) ((freeVolume / totalVolume) * 10);
            int i = 0;
            for ( ; i < MemUsage ; i++) {
                mfRect.setRect(5,(float) ssH+i*blockHeight,
			       blockWidth,(float) blockHeight-1);
                big.fill(mfRect);
            }
	    
            // .. Volume Used ..
            //
	    big.setColor(Color.green);
            for ( ; i < 10; i++)  {
                muRect.setRect(5,(float) ssH+i*blockHeight,
                                blockWidth,(float) blockHeight-1);
                big.fill(muRect);
            }
	    g.drawImage(bimg, 0, 0, this);
        }
	

	/**
	 * start the thread
	 */
        public void start() {
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setName("DataMonitor");
            thread.start();
        }

	/**
	 * stop the thread
	 */
        public synchronized void stop() {
            thread = null;
            notify();
        }

	/**
	 * run the thread
	 */
        public void run() {

            Thread me = Thread.currentThread();

            while (thread == me && !isShowing() || getSize().width == 0) {
                try {
                    thread.sleep(sleepAmount);
                } catch (InterruptedException e) { return; }
            }

            while (thread == me && isShowing()) {
                Dimension d = getSize();
                if (d.width != w || d.height != h) {
                    w = d.width;
                    h = d.height;
                    bimg = (BufferedImage) createImage(w, h);
                    big = bimg.createGraphics();
                    big.setFont(font);
                    FontMetrics fm = big.getFontMetrics(font);
                    ascent = (int) fm.getAscent();
                    descent = (int) fm.getDescent();
                }
                repaint();
                try {
                    thread.sleep(sleepAmount);
                } catch (InterruptedException e) { break; }
                if (DataMonitor.dateStampCB.isSelected()) {
                     System.out.println(new Date().toString() + " " + usedStr);
                }
            }
            thread = null;
        }

	/**
	 * set the data.
	 *
	 * @param temp a float array.
	 * @param size size of the array.
	 * @param status a status indicator
	 *
	 * @return a Galaxy frame to Hub.
	 */
	public void setData(float[] temp, int size, int status) {
	    
	    position = pts_received;
	    ptNum = pts_received;
	    pts_all[0] = (int)temp[0];
	    max_points = pts_received;
	}
    }
    
    /**
     * the main method
     */
    public static void main(String s[]) {
        final DataMonitor demo2 = new DataMonitor();
        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
            public void windowDeiconified(WindowEvent e) { demo2.surf.start(); }
            public void windowIconified(WindowEvent e) { demo2.surf.stop(); }
        };
        JFrame f = new JFrame("DataMonitor");
        f.addWindowListener(l);
        f.getContentPane().add("Center", demo2);
        f.pack();
        f.setVisible(true);

        demo2.surf.start();
    }
}

