package daruma.xml;

public class  QName
{
	//
	// XXX: This class is not completed yet.
	//      Loose checking are left.
	//

	private	String	qNamePrefix;
	private	String	qNameLocalName;
	private	boolean	valid;

	public	QName( String  qNameString )
	{
		this.valid = false;


		this.qNamePrefix = null;
		this.qNameLocalName = "";

		if ( qNameString == null )
		{
			return;
		}


		//
		// QName format: ([\i-[:]][\c-[:]]*:)?[\i-[:]][\c-[:]]*:)
		//

		String	s = qNameString.replaceAll( "[ \t\n\r]+" , " " )
								    .trim();

		if ( s.length() == 0
		  || s.endsWith( ":" ) )
		{
			return;
		}


		String[]	array = s.trim().split( ":" );

		for ( String  e : array )
		{
			if ( ! this.isValidNCName( e ) )
			{
				return;
			}
		}

		if ( array.length == 1 )
		{
			this.qNamePrefix    = null;
			this.qNameLocalName = array[0];
		}
		else if ( array.length == 2 )
		{
			this.qNamePrefix    = array[0];
			this.qNameLocalName = array[1];
		}
		else
		{
			return;
		}

		this.valid = true;
	}


	/**
	 * returns true if QName is well formed value or not.
	 */
	public	boolean	isValid()
	{
		return( this.valid );
	}


	/**
	 * returns prefix of QName
	 *
	 * If QName doesn't have prefix, returns null.
	 *
	 * If isValid() returns false, return value of getLocalName()
	 * is implementation defined.
	 */
	public	String	getPrefix()
	{
		return( this.qNamePrefix );
	}


	/**
	 * returns prefix of QName
	 *
	 * If QName doesn't have prefix, returns "".
	 *
	 * If isValid() returns false, return value of getLocalName()
	 * is implementation defined.
	 */
	public	String	getPrefixForPrint()
	{
		return( (this.qNamePrefix == null) ? "" : this.qNamePrefix );
	}


	/**
	 * returns local name of QName
	 *
	 * getLocalName() returns "" instead of null.
	 *
	 * If isValid() returns false, return value of getLocalName()
	 * is implementation defined.
	 */
	public	String	getLocalName()
	{
		return( this.qNameLocalName );
	}

	/**
	 * returns string QName value.
	 *
	 * toString() may return different value of initialized value
	 * specified with argument of constructor.
	 *
	 * If isValid() returns false, return value of getLocalName()
	 * is implementation defined.
	 */
	public	String	toString()
	{
		if ( this.qNamePrefix != null )
		{
			return( this.qNamePrefix + ":" + this.qNameLocalName );
		}
		else
		{
			return( this.qNameLocalName );
		}
	}


	private	boolean	isValidNCName( String  ncName )
	{
		// omit checking ':'

		// XXX: check first char of ncName

		return( ncName != null
		     && ncName.length() != 0 );
	}
}
