package com.eactive.eai.rms.client.service;

import org.springframework.beans.factory.InitializingBean;

import com.eactive.eai.rms.client.util.CommandParser;
import com.eactive.eai.rms.client.util.CommandUtils;
import com.eactive.eai.rms.client.util.WindowsSystemMon;

/**
 * The Class HostStatusService.
 * <ul>
 * <li>1. Function :</li>
 * <li>2. Summary :</li>
 * <li>3. Notification :</li>
 * </ul>
 * 
 * <pre> 
 * </pre>
 * 
 * 
 * 
 * @author  : $Author: 박기섭 $
 * @version : $Revision: 1.7 $
 */
public class HostStatusService implements InitializingBean {

    /** F/W logger. */
    private static com.eactive.eai.common.util.Logger logger = com.eactive.eai.common.util.Logger.getLogger(com.eactive.eai.common.util.Logger.LOGGER_CLIENT);

    static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows") ? true : false;
    
    private int TOTAL_MEMORY = 0;

    /**
     * Gets the cpu percentage.
     * 
     * @return the cpu percentage
     */
    public int getCpuPercentage() {
    	
        int result = 0;
        try {
        	if (IS_WINDOWS){
        		return WindowsSystemMon.getCpuPercentage();
        	}

        	String[] command = { "/bin/sh", "-c", "vmstat 1 2 | awk 'BEGIN{n=0;}{if(++n==4) { printf((100-$15));}}'" };

            CommandParser parser = new CommandParser() {
                public Object parse(String string) {
                    int result = 0;
                    try {
                        result = Integer.parseInt(string.trim());
                    } catch (Exception e) {
                    }
                    return result;
                }
            };

            result = (Integer) CommandUtils.processExec(command, parser);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }

        return result;
    }

    /**
     * Gets the disk percentage.
     * 
     * @param path the path
     * 
     * @return the disk percentage
     */
    public int getDiskPercentage(String path) {
        int result = 0;
        try {
        	if (IS_WINDOWS){
        		return WindowsSystemMon.getDiskPercentage();
        	}

            String command[] = new String[] {
                    "/bin/sh",
                    "-c",
                    "df -k " + path  + " | awk 'BEGIN{n=0;}{if(++n==2) { printf($5);}}'" };

            CommandParser parser = new CommandParser() {

                public Object parse(String string) {
                    int result = 0;
                    int psercentIndex = 0;
                    try {
                        psercentIndex = string.indexOf("%");
                        result = Integer.parseInt(string.substring(0, psercentIndex));
                    } catch (Exception e) {
                    }
                    return result;
                }
            };

            result = (Integer) CommandUtils.processExec(command, parser);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return result;
    }

    /**
     * Gets the memory percentage.
     * 
     * @return the memory percentage
     */
    public int getMemoryPercentage() {
    	int result = 0;

        try {
        	if (IS_WINDOWS){
        		return WindowsSystemMon.getMemoryPercentage();
        	}
        	
            String[] command = { "/bin/sh", "-c", "cat /proc/meminfo | egrep 'MemFree:|SwapFree' | awk 'BEGIN{t=0;}{t+=$2;}END {print t;}'" };
            
            CommandParser parser = new CommandParser() {
            	public Object parse(String string) {
            		int result = 0;
            		try {
            			result = Integer.parseInt(string.trim()) / 1024;
            		} catch (Exception e) {
            		}
            		return result;
            	}
            };

        	int freeMB = (Integer) CommandUtils.processExec(command, parser);
            result = (TOTAL_MEMORY - freeMB) * 100 / TOTAL_MEMORY;
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }

        if (logger.isDebugEnabled()) {
            logger.debug("getMemoryPercentage RESULT : " + result);
        }

        return result;
    }

    /**
     * 시스템의 전체 메모리 값을 구한다.
     *  
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
    	if (IS_WINDOWS){
    		return ;
    	}
        try {
            /*
             * 시스템의 전체 메모리 값을 구한다. 
             */
            /**
			[elink@dmccap01 ~]$ cat /proc/meminfo | grep MemTotal
			MemTotal:       28597244 kB
             */
        	String[] commandRealMemory = { "/bin/sh", "-c", "cat /proc/meminfo | grep MemTotal | awk '{printf($2)}'" };

            
            CommandParser realParser = new CommandParser() {
                public Object parse(String string) {
                    int realMemoryMB = 0;
                    try {
                        realMemoryMB = Integer.parseInt(string) / 1024;
                    } catch (Exception e) {
                        logger.warn(this, e);
                    }
                    return realMemoryMB;
                }
            };

            String[] commandPage = { "/bin/sh", "-c", "cat /proc/meminfo | grep SwapTotal | awk '{printf($2)}' " };
            CommandParser pageParser = new CommandParser() {
            	
            	public Object parse(String string) {
            		int pageMB = 0;
            		try {
            			pageMB = Integer.parseInt(string) / 1024;
            		} catch (Exception e) {
            			logger.warn(this, e);
            		}
            		return pageMB;
            	}
            };

            Integer realMemoryMB = (Integer) CommandUtils.processExec(
                commandRealMemory, realParser);

            Integer pageMB = (Integer) CommandUtils.processExec(commandPage,
                pageParser);

            this.TOTAL_MEMORY = realMemoryMB + pageMB;

            if (logger.isDebugEnabled()) {
                logger.debug("TOTAL MEMORY : " + TOTAL_MEMORY);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        HostStatusService service = new HostStatusService();
        service.afterPropertiesSet();
        // System.out.println("CPU : " + service.getCpuPercentage());
        // System.out.println("MEMORY : " + service.getMemoryPercentage());
        // System.out.println("DISK(/log) : " + service.getDiskPercentage("/log"));

    }
}
