/** 
	* Parser Class parseing user input and create Graph Class
	**/
import GCRawData.*;
import java.util.*;
import java.awt.*;

public class Parser {
	Vector read_buff;
	Vector ver;
	Vector ed1;
	Vector ed2;
	Graph gh;

	// constructor
	public Parser() {
		read_buff = new Vector();
		ver = new Vector();
		ed1 = new Vector();
		ed2 = new Vector();
	}
	
	// get Stack which has history about finding min-colors
	public Stack getGraphStack() {
		return gh.getStack();
	}
	
	// get min color with parameter which describes graph.
	public int getMinColor( String graph ) {
		try {
			preParserFunc( graph );
			return gh.getMinColor();
		} catch ( GraphException e) {
			return -1;
		}
	}
	
	// get min color
	public int getMinColor() {
		try {
			return gh.getMinColor();
		} catch (GraphException e) {
			System.out.println(e);
			return -1;
		}
	}
	
	// get Vertices min-colored with parameter which describe graph
	public Vertices getColorVertices( String graph ) {
		try {
			preParserFunc( graph );
			return gh.getColorVertices();
		} catch ( GraphException e) {
			System.out.println(e);
			return null;
		}
	}
	
	// get Vertices min-colored
	public Vertices getColorVertices() {
		return gh.getColorVertices();
	}
	
	// this function parsing user parameter and create Graph Class 
	// then perform OpenList which implemented in Graph Class
	private void preParserFunc( String graph ) throws GraphException {
		// parsing user input-String.
		try {
			StringTokenizer st = new StringTokenizer( graph, "{}" );
			
			int loop_size = st.countTokens();
			if (loop_size == 0) return;
			for ( int i=0; i< loop_size ; i++ ) {
				String read_token = st.nextToken();
				System.out.println( "[Debug] next token: "+read_token );
				if ( !read_token.equals(",") ) read_buff.add( read_token );
			}
		} catch(Exception e) {
			System.out.println( "[Debug] Exception at Java_HW1.main()" );
		}
		
		// parse and make vertices , edge
		StringTokenizer st2;
		String tmp2;
		// parse vertices
		try {
			tmp2 = (String)read_buff.elementAt(0);
			st2 = new StringTokenizer( tmp2, "," );	
			int tmp_int = st2.countTokens();
			for ( int i=0; i<tmp_int; i++ ) ver.add( st2.nextToken() );
		} catch( Exception e ) {
			System.out.println( "[Debug] Exception at Java_HW1.main(): parse vertices" );
		}
		// parse edges
		try {
			for ( int i=1; i<read_buff.size(); i++ ) { 
				tmp2 = (String)read_buff.elementAt(i);
				st2 = new StringTokenizer( tmp2, "," );
				if ( st2.countTokens() != 2 ) throw new GraphException("[Error] invalid edge: "+st2);
				ed1.add( st2.nextToken() );
				ed2.add( st2.nextToken() );
			}
		} catch(Exception e) {}
		try {
			// make new Graph Class
    	gh = new Graph( ver, ed1, ed2 );
    } catch( GraphException e ) {
      throw new GraphException(e.toString());
    }

	}//end of getMinColor()

}//end of class