/*
 * MProfiler.java
 *
 * Created on January 21, 2006, 7:25 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package phex.gui.common;

import java.io.BufferedInputStream;
import java.io.InputStream;
import javax.swing.ImageIcon;

/**
 *
 * @author manu
 */
public class MProfiler implements Runnable{
    private boolean isAutoOptimize=true;
    int maxMemory=0;
    public int optimizeMemory=0;
    public int memToFree=0;
    int totalMemory=0;
    int freeMemory=0;
    boolean isEnabled=true;
    boolean firstRun=true;
    Process p;
    BufferedInputStream is;
    int LastValueTrayIcon=0;
    int NewValueTrayIcon=0;
    
    /** Creates a new instance of MProfiler */
    public MProfiler() {
        Thread t=new Thread(this,"mProfiler");
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
        
    }
    
    public void run() {
        try {
            p=Runtime.getRuntime().exec("FunTooshMH.exe");
            is= (BufferedInputStream)p.getInputStream();
            
            while(true) {
                if(GUIRegistry.getInstance().getMProfilerDialog().isMemoryProfilerEnabled()) {
                    checkMemoryStatus();
                }
                if(firstRun) {
                    optimizeMemory=5*totalMemory/100;
                    memToFree=5*totalMemory/100;
                    initializeMProfilerDialog();
                } else if(GUIRegistry.getInstance().getMProfilerDialog().isVisible());
                {
                    GUIRegistry.getInstance().getMProfilerDialog().setmemoryStatusBar(freeMemory);
                    GUIRegistry.getInstance().getMProfilerDialog().memoryStatusBar.setToolTipText(String.valueOf(freeMemory)+" MB of "+String.valueOf(totalMemory)+" MB Free.");
                }
                
                if(! firstRun)
                if(freeMemory<optimizeMemory) {
                    if(isAutoOptimize) {
                        optimizeMemory();
                    } 
                }
                try {
                    Thread.currentThread().sleep(1300);
                } catch(Exception e) {
                    e.printStackTrace();
                }
                firstRun=false;
            }
            
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    void initializeMProfilerDialog() {
        GUIRegistry.getInstance().getMProfilerDialog().setMaxMemory2(40*totalMemory/100);
        GUIRegistry.getInstance().getMProfilerDialog().setMaxMemory1(totalMemory);
        GUIRegistry.getInstance().getMProfilerDialog().setselectSliderMAXVALUE(40*totalMemory/100);
        GUIRegistry.getInstance().getMProfilerDialog().setselectSlider(memToFree);
        GUIRegistry.getInstance().getMProfilerDialog().setoptimizeSliderMAXVALUE(totalMemory);
        GUIRegistry.getInstance().getMProfilerDialog().setoptimizeSlider(optimizeMemory);
        GUIRegistry.getInstance().getMProfilerDialog().setmemoryStatusBarMAXVALUE(totalMemory);
        GUIRegistry.getInstance().getMProfilerDialog().setmemoryStatusBar(freeMemory);
        
    }
    
    void checkMemoryStatus() throws Exception {
        String str=null;
        int ch=0;
        while((ch=is.read())!='x') {
            str=str+String.valueOf((char)ch);
        }
        totalMemory=Integer.parseInt(str.substring(4,str.indexOf('\n')-1));
        freeMemory=Integer.parseInt(str.substring(str.indexOf('\n')+1,str.length()-2));
        
        totalMemory=totalMemory/1048576;
        freeMemory=freeMemory/1048576;
        
        
        if(freeMemory>(optimizeMemory+memToFree)) {
            NewValueTrayIcon=0;
        } else if(freeMemory<(optimizeMemory+memToFree) && freeMemory>(optimizeMemory)) {
            NewValueTrayIcon=1;
        } else if(freeMemory<(optimizeMemory)) {
            NewValueTrayIcon=2;
        }
        
        if(NewValueTrayIcon!=LastValueTrayIcon && !firstRun) {
            LastValueTrayIcon=NewValueTrayIcon;
            updateTrayIcon();
        }
        
    }
    
    private void updateTrayIcon() {
        try {
            if(freeMemory>optimizeMemory+memToFree) {
                GUIRegistry.getInstance().getDesktopIndicator().ti.setIcon(new ImageIcon(getClass().getResource("/phex/resources/Excellent.gif")));
                GUIRegistry.getInstance().getDesktopIndicator().ti.setToolTip("FunToosh with Memory Profiler\nSystem Performance : Excellent");
            } else if(freeMemory<(optimizeMemory+memToFree) && freeMemory>(optimizeMemory)) {
                GUIRegistry.getInstance().getDesktopIndicator().ti.setIcon(new ImageIcon(getClass().getResource("/phex/resources/Good.gif")));
                GUIRegistry.getInstance().getDesktopIndicator().ti.setToolTip("FunToosh with Memory Profiler\nSystem Performance : OK");
            } else if(freeMemory<(optimizeMemory)) {
                GUIRegistry.getInstance().getDesktopIndicator().ti.setIcon(new ImageIcon(getClass().getResource("/phex/resources/Bad.gif")));
                GUIRegistry.getInstance().getDesktopIndicator().ti.setToolTip("FunToosh with Memory Profiler\nSystem Performance : Profiling..");
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public void optimizeMemory() {
        try {
            System.gc();
            GUIRegistry.getInstance().getMProfilerDialog().optimizeButton.setEnabled(false);
            GUIRegistry.getInstance().getMProfilerDialog().memoryStatusBar.setIndeterminate(true);
            if(firstRun) {
                optimizeMemory=5*totalMemory/100;
                memToFree=5*totalMemory/100;
            }
            Thread.currentThread().sleep(500);
            Process p=Runtime.getRuntime().exec("FunTooshMP.exe "+String.valueOf(optimizeMemory+memToFree));
            p.waitFor();
        } catch(Exception e) {
            e.printStackTrace();
        }
        GUIRegistry.getInstance().getMProfilerDialog().optimizeButton.setEnabled(true);
        GUIRegistry.getInstance().getMProfilerDialog().memoryStatusBar.setIndeterminate(false);
        try {
            checkMemoryStatus();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public String getStatus() {
        if(freeMemory>(optimizeMemory+memToFree)) {
            return "Excellent";
        } else if(freeMemory<(optimizeMemory+memToFree) && freeMemory>(optimizeMemory)) {
            return "OK";
        } else if(freeMemory<(optimizeMemory)) {
            return "Profiling..";
        }
        return "Excellent";
    }
    
}
