//------------------------------------------------------------------------------
// Lamp : Open source game middleware
// Copyright (C) 2004  Junpei Ohtani ( Email : junpee@users.sourceforge.jp )
//
// 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 (at your option) 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
//------------------------------------------------------------------------------

/** @file
 * ランダムリネーマ実装
 * @author Junpee
 */

#include "LampBasic.h"
#include "Core/Renamer/RandomRenamer.h"
#include "Core/Utility/Timer.h"

namespace Lamp{

//------------------------------------------------------------------------------
// コンストラクタ
RandomRenamer::RandomRenamer(){
	// タイマによりランダムの種初期化
	random_.setSeed(Timer::getTick().getValue());
}
//------------------------------------------------------------------------------
// コンストラクタ
RandomRenamer::RandomRenamer(u_int seed){
	random_.setSeed(seed);
}
//------------------------------------------------------------------------------
// デストラクタ
RandomRenamer::~RandomRenamer(){
}
//------------------------------------------------------------------------------
// リネーム
String RandomRenamer::rename(Database* database, const String& sourceName){
	// '_'以降を削除
	String result = sourceName;
	int underBarIndex = result.getIndexOf('_');
	Assert(underBarIndex != 0);
	if(underBarIndex > 0){
		result = result.getSubstring(0, underBarIndex);
	}
	// 素の名前が存在するかどうか
	if(!database->existName(result)){ return result; }
	// ランダムによる名前付けを行う
	String resultName;
	while(true){
		resultName.format("%s_%04x",
			result.getBytes(), (random_.get() & 0xffff));
		if(!database->existName(resultName)){ break; }
	}
	return resultName;
}
//------------------------------------------------------------------------------
} // End of namespace Lamp
//------------------------------------------------------------------------------
