package com.k_int.srusolr.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ExternalResourceResolver {
  private static final Log log = LogFactory.getLog(ExternalResourceResolver.class);
  
  public static ResourceBundle resolve(String bundle_location, String bundle_base_name, String tomcat_home_param) throws MalformedURLException, MissingResourceException{
    
    if (bundle_location==null || bundle_location.trim().equals("")) {
      throw new NullPointerException("Resource bundle location not set");
    } else {
      log.debug("Loading properties from "+bundle_location);
    }
    
    if (bundle_base_name==null || bundle_base_name.trim().equals("")) {
      throw new NullPointerException("Resource bundle base name not set");
    } else {
      log.debug("properties base name is "+bundle_base_name);
    }
    
    String tomcat_home    = System.getProperty(tomcat_home_param);
    URL resource_url      = new File(tomcat_home+"/"+bundle_location).toURI().toURL();
    URLClassLoader cl     = URLClassLoader.newInstance(new URL[]{resource_url});
    ResourceBundle bundle = ResourceBundle.getBundle(bundle_base_name, Locale.getDefault(), cl);
    
    return bundle;
  }
}
