/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.kiwi.cometd.utils;

import cz.kiwi.cometd.App;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author esner
 */
public class KiwiResourceLoader {
    final static Logger logger = LoggerFactory.getLogger(ConfigResourceBundle.class);
    
    private static KiwiResourceLoader kiwiResourceLoaderInstance;

    public static KiwiResourceLoader getInstance(){
        if (kiwiResourceLoaderInstance == null) {
            kiwiResourceLoaderInstance = new KiwiResourceLoader();
        }
 
        return kiwiResourceLoaderInstance;
    }
    
    public String getPropertyFromResource(String resource, String property) throws IOException {
        InputStream in = null;
        
        final Class<?> referenceClass = App.class;
        final URL url = referenceClass.getProtectionDomain().getCodeSource().getLocation();
        
        try{
            final File jarPath = new File(url.toURI()).getParentFile();
            in = new FileInputStream(jarPath + File.separator + resource);  //from jar directory  
        } 
        catch(final URISyntaxException e){
            logger.info(e.getMessage());
        }
        catch(final FileNotFoundException e){
            logger.info(e.getMessage());
        }
        
        if (in == null) //relative, from resources
            in = this.getClass().getClassLoader().getResourceAsStream(resource);
    
        Properties props = new Properties();
        
        props.load(in);
   
        return props.getProperty(property);
  }
    
}
