package  org.ts.ddcs.util;


import org.ts.ddcs.log.LogHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class SysIniCfg {

	private static Map configs = null;

	private static String iniName = null;
	public final static String TEMP_FILE_NAME = ".tempx";//临时文件后缀名
	public final static long BYTE_SIZE = 1024 ;//每次上传文件长度
	public static void init(String fileName) {

		try {
			iniName = fileName;
			configs = new HashMap(100);
			FileInputStream inStream = new FileInputStream(fileName);
			Properties prop = new Properties();
			prop.load(inStream);
			Collection col = prop.keySet();
			Iterator iter = col.iterator();
			while (iter.hasNext()) {
				Object strKey = iter.next();
				String tmp = (String) prop.get(strKey);
				configs.put(strKey, tmp);
			}
			//如果配置文件中没有配置文件上传路径，则从数据库中读取
			inStream.close();
		} catch (Exception e) {
			LogHelper.error(e.getMessage());
			e.printStackTrace();
		}
	}

	
	/**
	 * Get the config information by the key.
	 * 
	 * @param key
	 * @return String
	 */
	public static String get(Object key) {

		if("bytesize".equals(key)){
//			if(configs.get(key) != null && !"".equals(configs.get(key)) ){
//				return (String)configs.get(key);
//			}
//			else 
			return String.valueOf(BYTE_SIZE);
		}
		else if("fileurl".equals(key)){
			if(configs.get(key) != null && !"".equals(configs.get(key)) ){
				return (String)configs.get(key);
			}
			else{
					return (String)configs.get(key);
			}
		}
		else if("tempfilename".equals(key)){
			if(configs.get(key) != null && !"".equals(configs.get(key)) ){
				return (String)configs.get(key);
			}
			else return String.valueOf(TEMP_FILE_NAME);
		}
		else return (String) configs.get(key);
	}

	/**
	 * @param configs
	 *            The configs to set.
	 */
	public static void setConfigs(Map configs) {

		SysIniCfg.configs = configs;
	}

	public static int getInt(Object key) {

		int result = 0;

		try {
			result = Integer.parseInt(((String) configs.get(key)).trim());
		} catch (NumberFormatException e) {
			result = 0;
		}

		return result;
	}

	public static synchronized void store(Map props) {

		try {
			FileOutputStream os = new FileOutputStream(iniName);

			Iterator i = props.keySet().iterator();
			Object key;

			Properties ppt = new Properties();

			while (i.hasNext()) {
				key = i.next();
				ppt.put(key, props.get(key));
			}

			ppt.store(os, iniName);
			os.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
