/*
 * "Peko" Visual Novel System
 *
 * All Rights Reserved.
 * (c) Copyright 2002 by Tsukuba Bunko.
 *
 * $Id: ColorManager.java,v 1.1.2.1 2003/12/11 11:11:53 ppoi Exp $
 */
package tsukuba_bunko.peko.resource;

import	java.awt.Color;

import	java.util.Map;

import	java.lang.ref.WeakReference;

import	tsukuba_bunko.peko.Logger;


/**
 * 色の管理を提供します。
 * @author	$Author: ppoi $
 * @version	$Revision: 1.1.2.1 $
 */
public class ColorManager	{

	/**
	 * 唯一のインスタンス
	 */
	private static ColorManager	_instance = null;

	/**
	 * キャッシュ
	 */
	private Map	_cache = null;


	/**
	 * <code>ColorManager</code> のインスタンスを作成します。
	 */
	private ColorManager()
	{
		super();
	}


	/**
	 * 初期化を行います。
	 */
	private void initialize()
	{
		_cache = new java.util.HashMap( 89 );
		_cache.put( "black", new WeakReference(Color.black) );
		_cache.put( "white", new WeakReference(Color.white) );
		_cache.put( "red", new WeakReference(Color.red) );
		_cache.put( "blue", new WeakReference(Color.blue) );
		_cache.put( "green", new WeakReference(Color.green) );
		_cache.put( "yellow", new WeakReference(Color.yellow) );
		_cache.put( "gray", new WeakReference(Color.gray) );
		_cache.put( "darkGray", new WeakReference(Color.darkGray) );
		_cache.put( "lightGray", new WeakReference(Color.lightGray) );
		_cache.put( "cyan", new WeakReference(Color.cyan) );
		_cache.put( "magenta", new WeakReference(Color.magenta) );
		_cache.put( "orange", new WeakReference(Color.orange) );
		_cache.put( "pink", new WeakReference(Color.pink) );
		_cache.put( null, new WeakReference(Color.black) );
	}

	public Color getColor( String name )
	{
		Color	color = null;

		Object	cache = _cache.get( name );
		if( cache != null )	{
			color = (Color)((WeakReference)cache).get();
		}

		if( color == null )	{
			if( name.startsWith("#") )	{
				try	{
					color = new Color( Integer.parseInt(name.substring(1), 16) );
					WeakReference	ref = new WeakReference( color );
					_cache.put( name, ref );
				}
				catch( Exception e )	{
					Logger.error( "[resource] invalid color value specified. :" + name, e );
					Logger.debug( "[resource] using default color. (black)" );
					color = Color.black;
				}
			}
			else	{
				Logger.error( "[resource] invalid color name specified. :" + name );
				Logger.debug( "[resource] using default color. (black)" );
				color = Color.black;
			}
		}
		return color;
	}


	/**
	 * 唯一の <code>ColorManager</code> インスタンスを取得します。
	 * @return	唯一のインスタンス
	 */
	public static ColorManager getInstance()
	{
		if( _instance == null )	{
			synchronized( ColorManager.class )	{
				if( _instance == null )	{
					_instance = new ColorManager();
					_instance.initialize();
				}
			}
		}
		return _instance;
	}
}
