package id.iptek.utms.agent;

import id.iptek.utms.agent.util.IOUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class AppConfig {

    private static AppConfig self = null;
    private Logger logger = LoggerFactory.getLogger(AppConfig.class);
    private Properties props = new Properties();
    
    private AppConfig() {
    }

    public void init(String configFile) throws Exception {
        init(new File(configFile));
    }

    public void init(File configFile) throws Exception {
        InputStream in = new FileInputStream(configFile);
        try {
            props.load(in);
        } finally {
            IOUtil.close(in);
        }
    }

    public void set(String name, String value) {
        props.setProperty(name, value);
    }

    public String get(String name, String defaultValue) {
        String value = get(name);
        if(value == null) {
            value = defaultValue;
        }
        return value;
    }
    
    public String get(String name) {
        logger.trace("#get('{}');", name);
        String value =  props.getProperty(name);
        return value;
    }
    
    public int getAsInt(String name) {
        String value =  get(name);
        if(value != null) {
            return Integer.parseInt(value);
        }
        return 0;
    }
    
    public int getAsInt(String name, int defaultValue) {
        String value =  get(name);
        if(value != null) {
            return Integer.parseInt(value);
        }
        return defaultValue;
    }
    
    public boolean getAsBoolean(String name) {
        String value =  get(name);
        if(value != null) {
            return "true".equalsIgnoreCase(value);
        }
        return false;
    }
    
    public boolean getAsBoolean(String name, boolean defaultValue) {
        String value =  get(name);
        if(value != null) {
            return "true".equalsIgnoreCase(value);
        }
        return defaultValue;
    }
    
    public long getAsLong(String name) {
        return getAsLong(name, 0L);
    }
    
    public long getAsLong(String name, long defaultValue) {
        String value =  get(name);
        if(value != null) {
            return Long.parseLong(value);
        }
        return defaultValue;
    }
    
    public String[] getAll(String name) {
        String value = get(name);
        if(value != null) {
            return value.trim().split("\\s*,\\s*");
        }
        return new String[] {};
    }

    public Properties getProps() {
        return props;
    }
    
    public static AppConfig getInstance() {
        if (self == null) {
            self = new AppConfig();
        }
        return self;
    }
}
