package com.munjaon.client.server.service;

import java.io.FileInputStream;
import java.util.Properties;

/**
 * PropertyLoader
 * @author JDS
 */
public class PropertyLoader extends Thread {

    private static Properties props = load();
    private static PropertyLoader loader;

    public static String getProp(String key, String sub) {
        return get(key+"."+sub);
    }

    public static String get(String key) {
        return get(key, null);
    }

    public static String get(String key, String dflt) {
        if( props == null ) return null;

        String value = props.getProperty(key, dflt);

        if( value == null ) {
            value = dflt;
            System.err.println("Not Defined : [" + key + "]");
        }
        else {
            value = value.replaceAll("\\$SERVICE_HOME", System.getProperty("SERVICE_HOME"));
        }

        return value;
    }

    public synchronized static Properties load() {
        String propFile = System.getProperty("PROPS");
        try {
            Properties properties = new Properties();
            properties.load( new FileInputStream (propFile) );

            props = properties;
        } catch(Exception e) {
            Log(e);
        }
        
        if( loader == null ) {
            loader = new PropertyLoader();
            loader.start();
        }

        return props;
    }

    private synchronized static void Log(Object oLog) {
        if ( oLog instanceof Exception ) {
            System.out.println( (new java.util.Date()) );
            ((Exception)oLog).printStackTrace();
        } else {
            System.out.println( (new java.util.Date()) + (String) oLog );
        }
    }

    @Override
    public void run() {
        while( true ) {
            try {
                Thread.sleep(1000);
                load();
            } catch(Exception e) {
                Log(e);
            }
        }
    }

}
