import java.util.Iterator;

/** handles case of list (or sublist).
 * 
 * Simple:  use java.util.List rather than rolling our own
 * list, doing our own pointer manipulations
 * 
 * @author dlevine
 *
 */

public class IList implements Item {
	
	private java.util.List<Item> theList;
	
	
/** 
 * create and populate a list.
 * 
 * This is actually done in two steps:
 *  1. create the list object, which allows the parent (caller)
 *     to anchor it in the parent's structure.  (Otherwise, the
 *     partially complete list would not be visible outside of 
 *     this class/instance)
 *  2. then scan the items in input, adding them into the list.
 *  
 * note that the first symbol - a "(" has already been read...  
 *  that's how we decided to come here.
 *  
 * @author dlevine
 *
 */
	
	/**
	 * create (empty) list
	 */
	public IList() {
		theList = new java.util.ArrayList<Item>();
	}
	
	/**
	 *  populate the list
	 */
	public void readList(Tokenizer tz){
		// (have already read the opening "("
		assert "(".equals(tz.getCurrent().getSval());
		Token t = tz.getNext();
		while (! ")".equals(t.getSval())){
			// Ok, is it a sublist or an Atom?
			if ("(".equals(t.getSval())){
				// Sublist.  Create (and attach), then fill in
				IList subList = new IList();
				theList.add(subList);     // new sublist is our next elt.
				subList.readList(tz);
				assert ")".equals(tz.getCurrent().getSval());
				if (Lists.VERBOSE) {
					System.out.print(" Adding sublist");
					subList.print();
				}
			} else {
				Item i = new Atom(t);
				theList.add(i);
				if (Lists.VERBOSE) {
					System.out.print(" Adding ");
					i.print();
				}
			}
			t = tz.getNext();
		}
	
	}
	
	public void print() {
		//System.out.println("list: ");
		Iterator<Item> r = theList.iterator();
		System.out.print("(");
		while (r.hasNext()){
			Item t = r.next();
			t.print();
			if (r.hasNext())       // omit space after last item
				System.out.print(" ");
		}
		System.out.print(")");
	}
	
}
