package daruma.xml;

import daruma.xml.UniversalName;

import java.util.List;
import java.util.ArrayList;


public class SimpleXPath
{
	public	List<UniversalName>	path;
	public	UniversalName		attribute;

	public	SimpleXPath()
	{
		this.path = new ArrayList<UniversalName>();
		this.attribute = null;
	}

	public	SimpleXPath( SimpleXPath  simpleXPath )
	{
		if ( simpleXPath == null
		  || simpleXPath.path == null )
		{
			this.path = new ArrayList<UniversalName>();
		}
		else
		{
			this.path = new ArrayList<UniversalName>
							( simpleXPath.path );
		}

		if ( simpleXPath == null )
		{
			this.attribute = null;
		}
		else
		{
			this.attribute = simpleXPath.attribute;
		}
	}

	public	SimpleXPath( SimpleXPath  simpleXPath ,  UniversalName  name )
	{
		this( simpleXPath );

		this.add( name );
	}

	public	SimpleXPath( UniversalName  name ,  SimpleXPath  simpleXPath )
	{
		this();

		this.add( name );
		this.addPath( simpleXPath );
	}

	public	SimpleXPath( List<UniversalName> list )
	{
		this();
		this.path = list;
	}

	public	List<UniversalName>	getList()
	{
		return( this.path );
	}

	public	void	add( UniversalName  name )
	{
		this.path.add( name );
	}

	public	void	addAttribute( UniversalName  name )
	{
		//assert this.attribute == null;

		this.attribute = name;
	}

	public	void	addPath( SimpleXPath  additionalPath )
	{
		//assert this.attribute == null;

		this.path.addAll( additionalPath.path );
		this.attribute = additionalPath.attribute;
	}

	public	boolean	isAttribute()
	{
		return( this.attribute != null );
	}

	public	UniversalName	getAttributeName()
	{
		return( this.attribute );
	}


	public	String	toString()
	{
		return( this.getStringExpression() );
	}

	public	String  getStringExpression()
	{
		StringBuilder	buf = new StringBuilder();

		for( int  i = 0  ;  i < this.path.size()  ;  i ++ )
		{
			UniversalName	n = this.path.get(i);

			if ( i != 0 )
			{
				buf.append( "/" );
			}

			buf.append( n.toString() );
		}

		if ( this.attribute != null )
		{
			if ( buf.length() != 0 )
			{
				buf.append( "/" );
			}

			buf.append( "@" );
			buf.append( this.attribute.toString() );
		}

		return( buf.toString() );
	}

	public	boolean equals( SimpleXPath p )
	{
		if ( p == null
		     || p.path.size() != this.path.size() )
		{
			return false;
		}

		for( int  i = this.path.size() - 1 ;  i >= 0  ;  i -- )
		{
			if ( ! this.path.get(i).equals( p.path.get(i) ) )
			{
				return false;
			}
		}

		return true;
	}

	public	boolean equals( Object p )
		/* p should be an instance of SimpleXPath */
	{
		assert ( p instanceof SimpleXPath );
		return this.equals( (SimpleXPath)p );
	}

	public	int	hashCode()
	{
		int h = 0;

		for( int  i = 0  ;  i < this.path.size()  ;  i ++ )
		{
			h ^= this.path.get(i).hashCode();
		}

		return h;
	}
}
