/* $Id: IDGenerator.java,v 1.1 2007/10/29 02:55:37 nito Exp $
*
* Copyright (c)ARGO 21, Corporation. 2005, 2006.  All rights reserved.
* 
* This file is part of Nautica Workflow Core.
* 
*  Nautica Workflow Core 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
*  (at your option) any later version.
* 
*  Nautica Workflow Core 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 Nautica Workflow Core; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*  
*/
package jp.co.argo21.nautica.workflow.util;

import java.text.DecimalFormat;

import jp.co.argo21.nautica.workflow.util.StringUtils;

/**
 * 18桁以上で構成されるIDを生成するジェネレータ
 *
 * @author  Norihiro Itoh(ARGO 21 Corp.)
 * @version $Revision: 1.1 $
 * @since   Nautica Workflow 1.0
 */
public class IDGenerator
{
	private static DecimalFormat longFormatter
		= new DecimalFormat("0000000000000");

	private static DecimalFormat shortFormatter
		= new DecimalFormat("00000");

	private static long ms = System.currentTimeMillis();

	private static short num = 0;
	
	/**
	 * IDを生成する。動作中に時計が戻されたことを考慮し、
	 * 現在時刻が保持時刻より前の場合はカウンタの更新にとどめる。
	 * 
	 * @return ID
	 */
	public static synchronized String generate()
	{
		long t = System.currentTimeMillis();
		if (ms >= t) {
			num++;
		} else {
			ms = t;
			num = 0;
		}

		String s1 = longFormatter.format(ms);
		String s2 = shortFormatter.format(num);
		return (s1 + s2);
	}
	
	/**
	 * prefixで始まるIDを生成する。
	 * 
	 * @param prefix 前置文字列
	 * @return ID
	 */
	public static String generate(String prefix)
	{
		String s;
		if (StringUtils.checkNull(prefix)) s = "";
		else s = prefix;

		return (s + generate());
	}
	
	/**
	 * sに指定されたIDが空文字の時、または既存のIDがprefixで始まっていないとき
	 * 新しいIDを自動生成する。
	 * それ以外は、既存のIDをそのまま返す。
	 * 
	 * @param prefix 前置文字列
	 * @param s 既存のID
	 * @return ID
	 */
	public static String generate(String prefix, String s)
	{
		if (StringUtils.checkNull(s)) return generate(prefix);
		else if (StringUtils.checkNull(prefix)) return s;
		else if (s.startsWith(prefix)) return s;
		else return generate(prefix);
	}
}
