/*
 * Copyright 2007 Kickmogu Co. Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

package com.kickmogu;

import java.util.*;
import java.io.*;
import java.net.*;

public class Config extends Thread
{
	static String prop_file = null;
	static Properties props = null;
	static private Config instance;

	static {
		prop_file = System.getProperty("kickmogu.property");
		if (prop_file == null)
			prop_file = "kickmogu.properties";
		instance = new Config();
		instance.readProperty();
	}

	public void run() {
		try {
			ServerSocket ss = new ServerSocket(Integer.parseInt(Config.getProperty("kickmogu.Config.port")));
			Socket reread = ss.accept();
			reread.close();
			ss.close();
			readProperty();
		} catch (Exception ex) {
			System.out.println("Kickmogu.Config need property 'kickmogu.Config.port' .\n   " + ex);
		}
	}

	private synchronized void readProperty() {
		try {
			if (props == null) 
				props = new Properties();
			String[] prop = prop_file.split(",");
			if (prop_file.indexOf(File.separator) == -1)
				props.load(this.getClass().getClassLoader().getResourceAsStream(prop[0]));
			else
				props.load(new FileInputStream(prop[0]));
			for (int i = 1; i < prop.length; i++) {
				Properties opt_prop = new Properties();
				if (prop_file.indexOf(File.pathSeparator) == -1)
					opt_prop.load(this.getClass().getClassLoader().getResourceAsStream(prop[i]));
				else
					opt_prop.load(new FileInputStream(prop[i]));
				props.putAll(opt_prop);
			}
			Config cnf = new Config();
			cnf.setPriority(Thread.MIN_PRIORITY);
			cnf.setDaemon(true);
			cnf.start();
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("property file not found=" + prop_file + "\n   " + ex);
		}
	}

	static public int getInt(String key) {
		return Integer.parseInt(getProperty(key));
	}
	
	static public String getProperty(String key) {
		int f = -1, t = -1;

		String val = props.getProperty(key);
		if (val == null)
			return null;
		while ((f = val.indexOf("${")) > -1) {
			if ((t = val.indexOf("}")) == -1)
				break;
			String dest = props.getProperty(val.substring(f + 2, t));
			if (dest == null)
				break;
			val = val.replace(val.substring(f, t + 1), 
				props.getProperty(val.substring(f + 2, t)));
			
		}
		return val;
	}

	public static void main(String[] arg) {
		System.out.println(getProperty(arg[0]));
	}
}
