/*
 * "Peko" Visual Novel System
 *
 * All Rights Reserved.
 * Copyright (c) 1999-2003 Tsukuba Bunko.
 *
 * $Id: ActorHandler.java,v 1.1.2.1 2003/12/11 10:15:10 ppoi Exp $
 */
package tsukuba_bunko.peko.scenario.stage;

import	org.xml.sax.Attributes;

import	tsukuba_bunko.peko.Logger;

import	tsukuba_bunko.peko.canvas.stage.Actor;

import	tsukuba_bunko.peko.resource.ResourceManager;

import	tsukuba_bunko.peko.scenario.PSMLUtil;


/**
 * <samp>enter</samp>, <samp>move</samp>, <samp>exit</samp> を処理する <code>ElementHandler</code> です。
 * @author	$Author: ppoi $
 * @version	$Revision: 1.1.2.1 $
 */
public class ActorHandler	extends StageElementHandler	{

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


//
//	ContentHandler の実装
//
	public void startElement( String namespaceURI, String localName, String qName, Attributes attrs )
	{
		String	name = PSMLUtil.getAttributeValue( attrs, "name" );
		if( (name == null) || (name.length() == 0) )	{
			Logger.error( MessageIDs.SCN3001E, new Object[]{getSceneContext().getCurrentPath()} );
			return;
		}

		String	looks = PSMLUtil.getAttributeValue( attrs, "looks" );
		String	position = PSMLUtil.getAttributeValue( attrs, "position" );

		StageCoordinator	coordinator = getStageCoordinator();
		if( localName.equals("enter") )	{
			Actor	actor = new Actor( name );
			actor.setLooks( looks );
			setPosition( actor, ((position == null)?"center":position), "center" );
			coordinator.enter( actor );
		}
		else if( localName.equals("action") )	{
			Actor	actor = coordinator.getActor( name );
			if( actor == null )	{
				Logger.warn( MessageIDs.SCN3002W, new Object[]{name, getSceneContext().getCurrentPath()} );
			}
			else	{
				if( looks != null )	{
					actor.setLooks( looks );
				}
				setPosition( actor, position, null );
			}
			coordinator.action( actor );
		}
		else if( localName.equals("exit") )	{
			if( coordinator.exit(name) == null )	{
				Logger.warn( MessageIDs.SCN3002W, new Object[]{name, getSceneContext().getCurrentPath()} );
			}
		}

		String	effect = PSMLUtil.getAttributeValue( attrs, "effect" );
		if( effect == null )	{
			ResourceManager	resources = ResourceManager.getInstance();
			effect = (String)resources.getResource( ResourceIDs.DEFAULT_EFFECT_ACTOR, true );
		}
		coordinator.updateStage( effect );
	}

	protected void setPosition( Actor actor, String position, String defaultPosition )
	{
		if( position == null )	{
			return;
		}

		if( "center".equals(position) )	{
			actor.setPosition( Actor.POSITION_CENTER );
		}
		else if( "left".equals(position) )	{
			actor.setPosition( Actor.POSITION_LEFT );
		}
		else if( "right".equals(position) )	{
			actor.setPosition( Actor.POSITION_RIGHT );
		}
		else	{
			try	{
				actor.setPosition( Float.parseFloat(position) );
			}
			catch( Exception e )	{
				Logger.warn( MessageIDs.SCN3005W, new Object[]{getSceneContext().getCurrentPath()}, e );
				setPosition( actor, defaultPosition, null );
			}
		}
	}
}
