/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s): 
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */


package org.objectweb.jonas.common;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.naming.Context;


/**
 * This class manages reading of the properties used by EJB Server. 
 * This class adopts the singleton design-pattern. No need to instanciate it, 
 *  this is done by the private constructor called in the static reference.
 * This class provides as well a public constructor, to read other 
 *  properties files.
 */
public class JProp {

    public static final String JONASPREFIX = "jonas";

    static private Properties systEnv   = System.getProperties();
    static private String installRoot   = systEnv.getProperty("install.root");
    static private String fileSeparator = systEnv.getProperty("file.separator");
    static private String homeUser      = systEnv.getProperty("user.home");

    private Properties filesEnv       = new Properties();
    private Properties allEnv         = null;
    private String     propFileName   = null;
    private String[]   propFilesNames = new String[3];


    /**
     * Static method which return the JOnAS install root value.
     */
    public static String getInstallRoot() {
	// Check install.root system property
	if (installRoot == null) {
	    throw new RuntimeException("JOnAS configuration error: System property install.root not set!");
	}
	return(installRoot);
    }

    /**
     * Public constructor to initialize and read properties files.
     */
    public JProp(String fileName) throws Exception {
	readPropFiles(fileName);
    }

    /**
     * Public constructor to initialize and read JONAS properties files.
     */
    public JProp() throws Exception {
	readPropFiles(JONASPREFIX);
    }

    /**
     * Here are the rules to retrieve the properties.
     * Properties are first read in file getProperty("install.root")/config/fileName
     *  then overridden with values found in "$HOME/fileName" and then overridden 
     *  with values found in file "fileName".
     * These properties may be overridden again by system properties, given on the java 
     *  command line.
     */
    private void readPropFiles(String fileName) throws Exception {

	int filecount = 0;

	// Check install.root system property
	if (installRoot == null) {
	    throw new Exception("JOnAS configuration error: System property install.root not set!");
	}
	installRoot = installRoot.trim();

	// $JONAS_ROOT/config/fileName
	propFilesNames[0] = installRoot+fileSeparator+"config"+fileSeparator+fileName+".properties";
	// $HOME/fileName
	propFilesNames[1] = homeUser+fileSeparator+fileName+".properties";
	// ./fileName
	propFilesNames[2] = fileName+".properties";

	for (int i = 0; i < propFilesNames.length; i++) {
	    try {
		FileInputStream is = new FileInputStream(propFilesNames[i]);
		filesEnv.load(is);
		filecount++;
	    } catch (FileNotFoundException e) {
	    } catch (IOException e) {
		System.err.println(e);
	    }
	}

	if (filecount == 0) {
	    throw new FileNotFoundException("Cannot find properties for "+fileName);
	}

	allEnv = (Properties) filesEnv.clone(); 
	// Overriddes with syst properties
	if (fileName.equals("jonas")) {
	    for (Enumeration e = systEnv.keys(); e.hasMoreElements();) {
		Object key   = e.nextElement();
		String value = ((String)systEnv.get(key)).trim();
		allEnv.put(key, (Object)value);
	    }
	}
    }



    /**
     * Returns properties file name.
     *
     * @return JOnAS properties file name
     */
    public String getPropFile() {
	return propFileName;
    }

    /**
     * Returns properties files names
     *
     * @return JOnAS properties files names
     */
    public String[] getPropFiles() {
	return propFilesNames;
    }

    /**
     * Returns JOnAS environment as configured with files properties and
     *  system properties.
     * @return JOnAS properties
     */
    public Properties getEnv() {
	return allEnv;
    }


    /**
     * Returns JOnAS environment as configured with files properties only.
     *
     * @return JOnAS properties
     */
    public Properties getFilesEnv() {
	return filesEnv;
    }

    /**
     * Returns the value of the related property. With default values.
     *
     * @return property value
     */
    public String getValue(String key, String defaultVal) {
	
	String retProperty = allEnv.getProperty(key, defaultVal);
	return retProperty.trim();
    }

    /**
     * Returns the value of the related property.
     * The method returns null if the property is not found.
     *
     * @return property value, null if not exist
     */
    public String getValue(String key) {
	
	String retProperty = allEnv.getProperty(key);
	if (retProperty!=null) {
	    retProperty = retProperty.trim();
	}
	return retProperty;
    }

    /**
     * Returns the value of the related property as String [].
     * The method returns null if the property is not found.
     *
     * @return property value, null if not exist
     */
    public String[] getValueAsArray(String key) {
	
	String [] res = null;
	String value = this.getValue(key);
	if (value != null) {
	    StringTokenizer st = new StringTokenizer(value, ",");
	    res = new String [st.countTokens()];
	    int i = 0;
	    while (st.hasMoreTokens()) {
		res[i++] = st.nextToken().trim();
	    }
	}
	return res;
    }

    /**
     * String representation of the object for trace purpose
     * @return String representation of this object
     */
    public String toString() {
	String s = new String();
	for (Enumeration e = this.filesEnv.keys(); e.hasMoreElements();) {
	    Object key   = e.nextElement();
	    Object value = this.filesEnv.get(key);
	    s = s.concat("   " + key + " = " + value + "\n");
	}
	if (s.length()>0) {
	    // take of the last '\n'
	    s = s.substring(0, s.length()-1);
	}
	return(s);
    }

    /**
     * Bind all the properties found in file properties in a naming context
     * the naming context must be allocated by the caller
     */
    public void env2Ctx(Context ctx) throws Exception {
	Enumeration e = filesEnv.propertyNames();
	String key = null;
	while ( e.hasMoreElements() ) {
	    key = (String) e.nextElement();
	    ctx.bind( key, filesEnv.getProperty( key, "") );
	}
    }

    /**
     * Displays the JOnAS properties values, as they are set by the 
     *  different property files.
     */
    static public void main(String args[]) {
	
	JProp jonasProperties = null;
	try {
	    jonasProperties = new JProp("jonas");
	} catch (Exception e) {
	    System.err.println(e);
	    System.exit(2);
	}
	for (Enumeration e = jonasProperties.filesEnv.keys(); e.hasMoreElements();) {
	    Object key   = e.nextElement();
	    Object value = jonasProperties.filesEnv.get(key);
	    System.out.println(key.toString() + "=" + value.toString());
	}	
    }


}
