package be.msyben.vinylManager.tools.swing;

import be.msyben.vinylManager.properties.Language;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import javax.swing.JComponent;
import javax.swing.JProgressBar;

/**
 * Classe permettant d'afficher l'utiilsation de mémoire de d'effectuer un GC lors d'un clic.
 * Ne pas oublier le stop.
 * <p/>
 * @author Mathieu Syben
 */
public class MyMemoryComponent extends JComponent {

    private JProgressBar bar = new JProgressBar();
    private boolean run = true;

    public MyMemoryComponent() {
        bar.setMinimum(0);
        bar.setMaximum(100);
        bar.setStringPainted(true);
        bar.setCursor(new Cursor(Cursor.HAND_CURSOR));
        bar.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.gc();
            }
        });
        //bar.setSize(200,50);
        add(bar);
    }

    @Override
    public void setSize(int width, int height) {
        super.setSize(width, height);
        bar.setSize(width, height);
    }

    @Override
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        bar.setSize(width, height);
    }
    
    
    
    public void stop() {
        run = false;
    }

    public void run() {
        new Thread() {
            @Override
            public void run() {
                while (run) {
                    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
                    double used = memoryBean.getHeapMemoryUsage().getUsed();
                    double max = memoryBean.getHeapMemoryUsage().getMax();

                    int percent = (int) (100.0*(used / max));
                    bar.setValue(percent);
                    
                    String value = Language.getInstance().get("menu.info.memory").replace("%1", ""+percent);
                    
                    bar.setString(value);
                    
//                    System.out.println("La valeur used est de " + used);
//                    System.out.println("La valeur max est de " + max);
//                    System.out.println("La valeur est de " + percent);
//                    System.out.println();
                    
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException ex) {
                        
                    }
                }
            }
        }.start();
    }
}
