package hep.aida.ref;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author turri
 * @version $Id: AidaUtils.java,v 1.10 2005/02/14 22:36:29 serbo Exp $
 */
public abstract class AidaUtils
{
   private static Pattern pattern = Pattern.compile("(\\w+)\\s*((=\\s*(\"(.*?)\"|([^,;$]*)))\\s*)?(,|;|$)");
   /**
    * Parse AIDA options. Accepts values of the form:
    * <pre>
    * a=b;c=d
    * a="Some Options",c="My , Funny Value"
    * testCase     (equivalent to testCase=true)
    * </pre>
    * @param options The options string to be parsed
    * @return A map containing all the found options
    * @throws IllegalArgumentException if the options string is invalid
    */
   public static Map parseOptions(String options)
   {
      if (options == null || options.trim().length() == 0) return Collections.EMPTY_MAP;
      Map hashValues = new HashMap();
      Matcher matcher = pattern.matcher(options);
      while (matcher.find())
      {
         String key = matcher.group(1);
         String value = matcher.group(5);
         if (value == null) {
             value = matcher.group(6);
             //This is to remove the trailing spaces in group(6)
             if ( value != null )
                 value = value.trim();
         }
         if (value == null) value = "true";
         hashValues.put(key,value);
         if (matcher.end()  == options.length()) return hashValues;
      }
      throw new IllegalArgumentException("Invalid options: "+options);
   }
   
   // Creates path array from String. Path should start with "/"
   // Does not take escaped "/"  ("\\/") as a path element separator
    public static String[] stringToArray(String path) {
	String[] result = null;
	if ( path == null || path.equals("")) return result;
 
	StringTokenizer tokenizer = new StringTokenizer(path, "/");
	ArrayList list = new ArrayList(tokenizer.countTokens());
	while (tokenizer.hasMoreTokens()) {
	    String token = tokenizer.nextToken();
	    while (token.endsWith("\\")) {
		token = token.substring(0, token.length()-1)+ "/";
		if (tokenizer.hasMoreTokens()) token = token  + tokenizer.nextToken();
	    }
	    list.add(token);
	}
	result = new String[list.size()];
	list.toArray(result);

	return result;
    }

   // Escape all "/" -> "\\/"
   public static String modifyName(String name) {
       if (name.indexOf('/') < 0) return name;
       String newName = "";
       
       int index = -1;
       for (int i=0; i<name.length(); i++) {
           if (name.charAt(i) == '/') {
               if (i > 0 && name.charAt(i-1) == '\\') continue;
               if (i > index) {
                    newName = newName + name.substring(index+1, i) + "\\/";
                    index = i;
               } else if (i == index) {
                   newName = newName + "\\/";
               }
           }
       }
       newName += name.substring(index+1);
       
       return newName;
   }

   public static String parseName(String pathString) {
       if (pathString == null || pathString.equals("/")) return "";
       String[] path = stringToArray(pathString);
       String name = path[path.length-1];
       return name;
   }
   
   public static String parseDirName(String pathString) {
       if (pathString == null || pathString.equals("/")) return pathString;
       String dirName = "";
       String[] path = stringToArray(pathString);
       if (path.length <= 1) return dirName;
       else {
           dirName = "/";
           for (int i=0; i<path.length-1; i++) { dirName += path[i] + "/"; }
       }
       return dirName;
   }
   
}
 
