package daruma.xml.util;

import daruma.util.ParseException;

import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XPointerUtil
{
    private XPointerUtil()
    {
    }

    public static Map<String, String> parseXmlnsString( String xmlnsString )
	throws ParseException
    {
	Pattern p1 = Pattern.compile( "^xmlns\\(([^\\)]*)\\)$" );
	Matcher m1 = p1.matcher( xmlnsString );

	String errorMessage = "invalid format xmlns string ["
			      + xmlnsString + "], expected was ["
			      + "xmlns(foo=http://...,bar=http://...)";

	if ( ! m1.find() )
	{
	    throw new ParseException( errorMessage );
	}

	Map<String, String> ret = new TreeMap<String, String>();

	Pattern p2 = Pattern.compile( "^([^=,\\)]*)=([^=,\\)]*)$" );

	for ( String v : m1.group(1).split( "," ) )
	{
	    Matcher m2 = p2.matcher( v );

	    if ( ! m2.find() )
	    {
		throw new ParseException( errorMessage );
	    }

	    ret.put( m2.group(1), m2.group(2) );
	}

	return ret;
    }
}
