/*
 * Copyright (C) 1999-2006 <a href="mailto:adrian.paschke@gmx.de">Adrian Paschke</a>
 * 
 * The RBSLM Environment is part of the Rule Based Service Level Agreement (RBSLA)
 * framework, available at 
 * <a href=" http://ibis.in.tum.de/staff/paschke/rbsla/index.htm">RBSLA</a>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package rbsla.environment.view;

import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.log4j.Logger;



/**
 * Parse Results of the Inference process.
 */
public class ParseResults {

    private static Logger logger = Logger.getLogger(ParseResults.class);
    
    // Singelton
    private ParseResults()
    {    
    }
    
    static private ParseResults instanceObj = null; 
    static public ParseResults instance()
    {
    	if (instanceObj==null)
    		instanceObj = new ParseResults();
    	return instanceObj;
    }

    public String parseManyResults(String result)
    {

        String cleanString = "";

            if (result != null)
        {
            StringTokenizer tokenizer = new StringTokenizer(result, "\n", false);
            while (tokenizer.hasMoreElements())
            {
                String s = tokenizer.nextToken();
                try
                {                   
                    cleanString += parseString(s) + "\n";
                } catch (Exception ex)
                {
                    logger.info("", ex);
                    cleanString += s;
                }
            }
        }
        return cleanString;

    }

    public String parseString(String result)
    {
        StringTokenizer tokenizer = new StringTokenizer(result, ",()", true);
        Vector tokenVector = new Vector();
        while (tokenizer.hasMoreElements())
        {
            String s = tokenizer.nextToken();
            tokenVector.add(s);
        }
        if (tokenVector.size() <= 1)
            return result;

        int pos = 0;
        Node rootNode = new Node("Arsch", null);
        Node parentNode = rootNode;
        while (pos < tokenVector.size())
        {
            String now = (String) tokenVector.get(pos);
            String ahead = "";
            if (pos + 1 < tokenVector.size())
                ahead = (String) tokenVector.get(pos + 1);

            if (ahead.equals("("))
            {
                parentNode = new Node(now, parentNode);
                pos++;
            } else if (now.equals(")"))
                parentNode = parentNode.getParent();
            else if (now.equals(","))
                ;
            else
                new Node(now, parentNode);
            pos++;
        }
        if (rootNode.childs.size() == 1)
            rootNode = (Node) rootNode.childs.get(0);
        return getCleanString(rootNode);
    }

    String getCleanString(Node node)
    {
        String r = "";
        if (node.getChilds().size() > 0)
        {
        	Vector childs = node.getChilds();
        	String name = format(((Node) childs.lastElement()).getName());
        	
        	String rr ="";
            for (int i = childs.size()-1; i >= 0; i--)
            {
            	String s = getCleanString((((Node) childs.get(i))));
            	if (!s.equals(""))
            	{
            	    if (!rr.equals("")) rr+=",";
            	    rr += s;	
            	}
            }
            
            
            if (!(rr.equals("") && name.equals("")))
            {
            	if (name.equals("list")) r += "(" + rr + ")"; 
          
            	else	{
            	    r += name;
            	    if (!rr.equals("")) r +=",";
            	    r += rr;
            	}
            }
        	
/*        	String name = format(((Node) childs.lastElement()).getName());
        	if (childs.size()==0) ; 
        	else {        		
        		r += getCleanString((((Node) childs.get(0)))) + ",";	
        	
        	String rr = "";
            for (int i = 1; i < childs.size(); i++)
            {
            	rr += getCleanString((((Node) childs.get(i))));	
            	if (i+1!=childs.size()) rr += "#";
            }
            if (true) {
        		if (name.equals("list")) r+="[" + rr + "]"; 
        		else r += name + "(" + rr + ")";
        	}        	
        	}*/
        }
        return r;
    }

    String format(String s)
    {
        if (s.startsWith("[") && s.endsWith("]"))
            return s.substring(1, s.length() - 1);
        else
            return s;

    }
    public static void main(String[] argv)
    {
    String s = "list(list(list([],list(list(list(list([],[false]),list(list(list(list(list(list(list([],[10]),[2]),[0]),[1]),[1]),[2004]),[datetime])),list(list(list(list(list(list(list([],[10]),[2]),[0]),[1]),[1]),[2004]),[datetime])),[timeintervall])),list(list(list(list([],[false]),list(list(list(list(list(list(list([],[55]),[1]),[0]),[1]),[1]),[2004]),[datetime])),list(list(list(list(list(list(list([],[10]),[1]),[0]),[1]),[1]),[2004]),[datetime])),[timeintervall])),list(list(list(list([],[false]),list(list(list(list(list(list(list([],[35]),[0]),[0]),[1]),[1]),[2004]),[datetime])),list(list(list(list(list(list(list([],[15]),[0]),[0]),[1]),[1]),[2004]),[datetime])),[timeintervall]))";
    String ss = ParseResults.instance().parseString(s);
    logger.info(ss);
    }    
}

    // root is null
    // double linked tree
    class Node
    {
        private static Logger logger = Logger.getLogger(AdvancedTextViewer.class);

        String name;

        Node parent;

        Vector childs = new Vector();

        public Node(String _name, Node _parent)
        {
            name = _name;
            parent = _parent;
            if (parent != null)
                parent.childs.add(this);
        }

        public Node getParent()
        {
            return parent;
        }

        public Vector getChilds()
        {
            return childs;
        }

        public String getName()
        {
            return name;
        }

    }

 

