/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.kiwi.cometd.utils;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author esner
 */
public class ConfigResourceBundle {  
  final static Logger logger = LoggerFactory.getLogger(ConfigResourceBundle.class);
 
  private Document doc = null;
  
  private static ConfigResourceBundle configResourceBundleInstance;
  
  public static ConfigResourceBundle getInstance(){
        if (configResourceBundleInstance == null) {
            configResourceBundleInstance = new ConfigResourceBundle();
            try {
                configResourceBundleInstance.loadConfigXML();
            } catch (IOException ex) {
                logger.error(ex.getMessage());
                return null;
            }
        }
        
        return configResourceBundleInstance;
  }
  
  public String getObject(String key) {
        if (doc == null || key == null)
            return null;
      
        NodeList list = doc.getElementsByTagName(key);
        
        if (list != null && list.getLength() > 0)
            return list.item(0).getTextContent();
      
        return null;
  }
    
  
  public void loadConfigXML() throws IOException {
        String configLocation = KiwiResourceLoader.getInstance().getPropertyFromResource(CometdClientUtils.RESOURCE_NAME, CometdClientUtils.CONFIG_LOCATION_KEY);
        
        logger.info("Loaded config location: " + configLocation);
        
        File file = new File(configLocation);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            logger.error(ex.getMessage());
        }
        
        try {
            doc = docBuilder.parse(file);
            doc.getDocumentElement().normalize();
        } catch (SAXException ex) {
            logger.error(ex.getMessage());
        }
            
        return;
  }
}